Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to LINQ.SelectMany with constant number of inner elements

Tags:

c#

linq

I am trying to determine if there is a better way to execute the following query:

I have a List of Pair objects.

A Pair is defined as

public class Pair
{
    public int IDA;
    public int IDB;
    public double Stability;
}

I would like to extract a list of all distinct ID's (ints) contained in the List<Pair>.

I am currently using

var pIndices = pairs.SelectMany(p => new List<int>() { p.IDA, p.IDB }).Distinct().ToList();

Which works, but it seems unintuitive to me to create a new List<int> only to have it flattened out by SelectMany.

This is another option I find unelegant to say the least:

var pIndices = pairs.Select(p => p.IDA).ToList();
pIndices.AddRange(pairs.Select((p => p.IDB).ToList());
pIndices = pIndices.Distinct().ToList();

Is there a better way? And if not, which would you prefer?

like image 478
Rotem Avatar asked Dec 06 '22 10:12

Rotem


2 Answers

You could use Union() to get both the A's and B's after selecting them individually.

var pIndices = pairs.Select(p => p.IDA).Union(pairs.Select(p => p.IDB));
like image 82
Jon B Avatar answered Dec 10 '22 03:12

Jon B


You could possibly shorten the inner expression to p => new [] { p.IDA, p.IDB }.

like image 37
Wiktor Zychla Avatar answered Dec 10 '22 02:12

Wiktor Zychla