如何从linq查询的输出获取类列表

时间:2018-06-28 15:14:47

标签: c# linq

请参见以下代码:

public class Element
{
    public int num { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public Element(int _num, string _name, int _age)
    {
        this.num = _num;
        this.name = _name;
        this.age = _age;
    }
}

List<Element> ItemCollection = new List<Element>();
ItemCollection.Add(new Element(1, "A", 25));
ItemCollection.Add(new Element(1, "B", 25));
ItemCollection.Add(new Element(1, "C", 25));
ItemCollection.Add(new Element(2, "B", 15));
ItemCollection.Add(new Element(3, "ada", 25));
ItemCollection.Add(new Element(3, "As", 25));
ItemCollection.Add(new Element(4, "as", 25));
ItemCollection.Add(new Element(5, "Asd", 25));
ItemCollection.Add(new Element(6, "Asd", 25));
ItemCollection.Add(new Element(6, "Asd", 23));

//Case of uniqueness
var UniqueNumberCollection = (from i in ItemCollection
                              where i.age > 20
                              group i by i.num into eCollection
                              where eCollection.Count() == 1                                          
                              select eCollection.Key).ToList();

以上代码给我的输出为4,5

但是我希望输出为4, "as", 25 and 5, "Asd", 25

换句话说,我希望整个元素不仅仅是数字输出

1 个答案:

答案 0 :(得分:1)

GroupBy的作用是通过Key(您当前选择的唯一内容)将元素分组到一个集合中。

当您说想要整个元素时,您需要意识到自己想要该集合的First()FirstOrDefault(),否则您将仍然要处理列表。

鉴于您添加到问题中的内容,这似乎是您想要的:

var UniqueNumberCollection = (from i in ItemCollection
                              where i.age > 20
                              group i by i.num into eCollection
                              where eCollection.Count() == 1                                          
                              select new { eCollection.Key, eCollection.FirstOrDefault().name, eCollection.FirstOrDefault().age }).ToList();