开发者

Linq solution for list of object?

int count = 0;
foreach (Treatment treatment in DeclarationContent.Treatments)
{
    if (treatment.Treatm开发者_如何学CentNumber == treatmentNumber)
        break;

    count++;
}

I want to have a Linq statement for above foreach statement.


var count = DeclarationContent.Treatments
                              .TakeWhile(t => t.TreatmentNumber != treatmentNumber)
                              .Count();

This uses TakeWhile to only count all the treatments until some treatmentnumber is equal to your argument. You can't use .Where() here (as other answers state) because that will not be the same semantic as your foreach has (however, it may be what you want ;-) )

Updated: I see you want the index, in that case you can also do like this (and .Treatment instead of .Index if you want the Treatment object.):

var index = DeclarationContent.Treatments
                              .Select((t, i) => new { Index = i, Treatment = t })
                              .First(pair => pair.Treatment.TreatmentNumber == treatmentNumber)
                              .Index;

Note: You might have to replace DeclarationContent.Treatments with DeclarationContent.Treatments.Cast<Treatment>() as noted in a comment.


int count = DeclarationContent.Treatments.TakeWhile(treatment.TreatmentNumber == treatmentNumber).Count();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜