C # / LINQ select counting objects with same properties

I am starting with LINQ and I would like to know if it can be used 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 objects myClass.

public List<myClass> myList;

Can I easily get from LINQ subscriptions myListcontaining all objects myClassfor which the property value is Textpresent more than once.

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 be the objects Aand Bin my sublist

+3
source share
2 answers

Maybe not perfect, 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 the 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
+5
source

It works:

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

Testing 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; }}
+1
source

Source: https://habr.com/ru/post/1713758/


All Articles