Reputation: 1564
I have a generic list:
List<Test> lstReport = new List<Test>();
lstReport.Add(new Test { ID = 1, Category = "Hot work", Approver = "Praveen" });
lstReport.Add(new Test { ID = 1, Category = "Civil work", Approver = "Praveen" });
lstReport.Add(new Test { ID = 1, Category = "Others", Approver = "Praveen" });
lstReport.Add(new Test { ID = 4, Category = "Hot work", Approver = "Praveen" });
lstReport.Add(new Test { ID = 5, Category = "Critical work", Approver = "Praveen" });
Now I want to take unique rows from the generic list by the ID value. For eg, I need to group the rows having same ID and if the existence of ID's more than once, then its Category field has to be changed to "Grouped".
How can I write this expression?
Upvotes: 0
Views: 1067
Reputation: 30022
This Works:
var QueryResult = (from x in lstReport
group x by x.ID into res
select new Test
{
ID = res.Key,
Category = res.Count() > 1 ? "Grouped" : res.First().Category,
Approver = res.First().Approver
}).ToList();
Upvotes: 1
Reputation: 3185
You can use Linq to group objects based on some property:
var list = lstReport.GroupBy(t => t.ID);
This will return a new collection with 3 items: IEnumerable<IGrouping<TKey, TSource>>
; which basically means a collection containing a collection with one or more items.
Then you can iterate over that new collection and check if each item contains more than one subitem; if it does, then iterate over the subitems and modify the Category value.
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.groupby(v=vs.110).aspx
Upvotes: 0
Reputation: 3937
List<Test> lstReport = new List<Test>();
...
var groups = lstReport.GroupBy(i => i.ID).ToList();
foreach(var group in groups) {
var items = group.ToList();
if(items.Count > 1)
items.ForEach(i => { i.Category = "Grouped"; });
}
Upvotes: 1
Reputation: 19843
You can try this
var q = from r in lstReport
group r by r.ID into g
select new Test{ID=g.Key, Category = g.Count()>1? "Grouped" : g.Min(Category)};
also you can have g.Max(...) or g.Min(...)
Upvotes: 0