Search code examples
c#linq

How to convert object properties to list using linq?


Say there is a pair model that has a FirstId and a SecondId Guid property. I want to create a list of ids. Right now I am doing it like this:

var ids = new List<Guid> { };

payload.Pairs
    .ToList()
    .ForEach(x =>
    {
        ids.Add(x.FirstId);
        ids.Add(x.SecondId);
    }); 

Is there some magic method within linq that can do that instead of ForEach?


Solution

  • Use SelectMany:

    ids = payload.Pairs.SelectMany(p => new[]{ p.FirstId, p.SecondId }).ToList();