TakeWhile LINQ method not giving result as expected
I am expecting the string which has "i" but getting empty results. Can you tell me th开发者_Python百科e reason?
PetOwner[] petOwners = { new PetOwner { Name = "sen", Pets = new List { "puppy", "tiger" } }, new PetOwner { Name = "sugu", Pets = new List { "jimmy", "rose" }}
}; var pets = petOwners.SelectMany(p => p.Pets);
var pets1 = pets.TakeWhile<string>(s => { Console.WriteLine(s); return s.Contains("i"); });
Don't use TakeWhile
for this - it terminates the loop as soon as it encounters an element for which the expression returns false. Use Where
instead. Also just use an ordinary foreach loop to do the output instead of putting the call to WriteLine inside the lambda function. This makes it much easier to understand your code.
var petsContainingI = petOwners.SelectMany(p => p.Pets).Where(s => s.Contains("i"));
foreach (string s in petsContainingI)
{
Console.WriteLine(s);
}
精彩评论