views:

14

answers:

1

Hi, I am expecting the string which has "i" but getting empty results. Can you tell me the 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"); });
+1  A: 

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);
}
Mark Byers