Reputation: 381
See following code:
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();
Above code gives me the output as 4,5
But I want the output as 4, "as", 25 and 5, "Asd", 25
In other words i want entire element as output not the just the numbers
Upvotes: 1
Views: 527
Reputation: 6460
What the GroupBy
does is it groups the elements into a collection by the Key
(the only thing you're currently selecting).
When you say you want the entire element, you need to realize you either want First()
or FirstOrDefault()
of that collection, or you're going to still be dealing with a list.
Given what you added to your question, this seems like something you'd want :
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();
Upvotes: 1