C#/ LINQ选择具有相同属性的对象子列表

时间:2009-07-28 13:18:35

标签: c# linq

我是LINQ的初学者,我想知道是否可以用它来解决以下问题:

我有一个班级:

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

我有一个myClass个对象列表。

public List<myClass> myList;

我是否可以轻松地使用myList子列表来包含属性myClass的值不止一次的所有Text个对象。

例如,如果我有

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 });

我的子列表中应该有对象AB

2 个答案:

答案 0 :(得分:5)

也许不理想,但也许:

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

或者在查询语法中:

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

答案 1 :(得分:1)

这有效:

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

测试程序:

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; }}