Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model this as a LINQ query?

Tags:

c#

.net

linq

I have the following classes:

public class A
{
    public string P1 {get;set;}
    public string P2 {get;set;}
    public string P3 {get;set;}
    public string P3 {get;set;}
}

public class Id
{
    public string Main {get;set;}
    public string SubMain {get;set;}
}

Having a List I need to return a List with all the pairs P1 - P2 that are different in the List.

So if in the list I have:

 P1 = "A" - P2 "B"
 P1 = "A" - P2 "C"
 P1 = "B" - P2 "B"
 P1 = "A" - P2 "B"

I need to return a List with 3 Id like:

 Main = "A" - SubMain "B"
 Main = "A" - SubMain "C"
 Main = "B" - SubMain "B"

Is this possible with just one LINQ query? I would say yes but I'm not very comfortable with the Select statement.

Thanks in advance.

like image 249
Ignacio Soler Garcia Avatar asked Nov 26 '25 02:11

Ignacio Soler Garcia


1 Answers

You can use the Tuple class, it will do all the work on the distincts for you :

myList.Select(a => Tuple.Create(a.P1, a.P2))
      .Distinct()
      .Select(tuple => new Id() { Main = tuple.Item1, SubMain = tuple.Item2 } )
      .ToList();

The advantage is that Tuple class already override members like Equals, GetHashCode, all you need for performing a Distinct on a collection.

like image 62
Cyril Gandon Avatar answered Nov 28 '25 14:11

Cyril Gandon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!