Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/LINQ select sublist of objects with same properties

Tags:

c#

linq

I'm a beginner with LINQ and I would like to know if it is possible to use it to solve the following problem:

I have a class :

public class myClass
{
  public int Id { get; set; }
  public int Category { get; set; }
  public string Text { get; set; }
}

And I have a list of myClass objects.

public List<myClass> myList;

Can I easily get with LINQ the sublist of myList containing all the myClass objects for which the value of the property Text is present more than once.

for instance if I have

myClass A = new myClass { Id=1, Category=1, Text="Hello World!"};
myClass B = new myClass { Id=2, Category=2, Text="Hello World!"};
myClass C = new myClass { Id=3, Category=2, Text="Good Bye!"};
myList.AddRange(new []{ A, B, C });

I should have objects A and B in my sublist

like image 312
pierroz Avatar asked Oct 19 '25 13:10

pierroz


2 Answers

Perhaps not ideal, but maybe:

var result = myList.GroupBy(x=>x.Text).Where(grp => grp.Count() > 1)
            .SelectMany(x=>x); // .ToList() if you want a list

Or in query syntax:

var result = from x in myList
             group x by x.Text into grp
             where grp.Count() > 1
             from y in grp
             select y; // .ToList() if you want a list
like image 169
Marc Gravell Avatar answered Oct 22 '25 02:10

Marc Gravell


This works:

  var sublist = (from a in myList
                from b in myList
                where a.Text == b.Text
                   && a.Id != b.Id
                select a).Distinct();

Test Program:

void Main()
{

    myClass A = new myClass { Id=1, Category=1, Text="Hello World!"};
    myClass B = new myClass { Id=2, Category=2, Text="Hello World!"};
    myClass C = new myClass { Id=3, Category=2, Text="Good Bye!"};
    myClass D = new myClass { Id=4, Category=7, Text="Hello World!"};
    List<myClass> myList = new List<myClass>(); 
    myList.AddRange(new []{ A, B, C, D });

      var sublist = (from a in myList                
      from b in myList                
      where a.Text == b.Text                   
      && a.Id != b.Id                
      select a).Distinct();

      sublist.Dump();
}
public class myClass{  public int Id { get; set; }  public int Category { get; set; }  public string Text { get; set; }}
like image 32
cjk Avatar answered Oct 22 '25 04:10

cjk



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!