tags:

views:

624

answers:

2

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

+2  A: 

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
Marc Gravell
I vote for this one which works great indeedand for the moment I prefer the query syntax, easier to understand for me :)
PierrOz
+1  A: 

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; }}
ck
That works when there are 2 matches, but explodes when there are more; so 3 matches results in 6 results, etc.
Marc Gravell
@Marc - distinct added to fix :)
ck