Home > Net >  How to convert object properties to list using linq?
How to convert object properties to list using linq?

Time:12-17

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?

CodePudding user response:

Use SelectMany:

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

CodePudding user response:

Alongside SelectMany, if you're looking to add them to an existing list, the AddRange function is the best to use:

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

CodePudding user response:

Your approach could be translated to Linq's Aggregate function

var ids = payload.Pairs.Aggregate(
    seed: new List<Guid>(),
    func: (agg, item) => {
        agg.AddRange(new[] { item.FirstId, item.SecondId });
        return agg;
    },
    resultSelector: agg => agg);

If your payload.Pairs is already materialized and it is not an IEnumerable then you can do some memory optimisation like this

var ids = payload.Pairs.Aggregate(
    seed: new List<Guid>(payload.Pairs.Count * 2),
    func: (agg, item) => {
        agg.Add(item.FirstId);
        agg.Add(item.SecondId);
        return agg;
    },
    resultSelector: agg => agg);

Here is a working example on dotnet fiddle.

  • Related