1

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?

4 Answers 4

6

Use SelectMany:

ids = payload.Pairs.SelectMany(p => new[]{ p.FirstId, p.SecondId }).ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

Yet another type of solution could be to use two stream of guids

var firstIds = payload.Pairs.Select(item => item.FirstId);
var secondIds = payload.Pairs.Select(item => item.SecondId);

and then depending on the fact the ordering matters or not you can use Zip or Concat respectively.

firstIds.Concat(secondIds);
//OR
firstIds.Zip(secondIds, (f, s) => new[] { f, s }).SelectMany(x => x);

Related dotnet fiddle

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.