How can I return a value from .NET IGrouping using a key?

I'm struggling to figure out how to get the Value part of an IGrouping instance.

I have the following:

 IList<IGrouping<string, PurchaseHistory> results = someList.GroupBy(x => x.UserName); 

And now I want to iterate over each collection and extract purchase histories for this user (and check if there are any things in the purchase history collection).

+5
source share
3 answers

how about a nested loop?

 IList<IGrouping<string, PurchaseHistory>> results = someList.GroupBy(x => x.UserName); foreach (IGrouping<string, PurchaseHistory> group in results) { foreach (PurchaseHistory item in group) { CheckforStuff(item); } } 

or one loop with linq expression

 IList<IGrouping<string, PurchaseHistory>> results = someList.GroupBy(x => x.UserName); foreach (IGrouping<string, PurchaseHistory> group in results) { bool result = group.Any(item => item.PurchasedOn > someDate); } 
+6
source

Call..

 IList<IGrouping<string, PurchaseHistory> results = someList .GroupBy(x => x.UserName); .Select(result => (result.Key, result.Any(SomeStuffExists))); 

WITH..

 bool SomeStuffExists(PurchaseHistory item) { return .. } 

gives tuples in the form ..

  • ("UserNameX", true)
  • ("UserNameY", false)
  • ..
0
source

This is so if you want to iterate over all elements

 foreach (IGrouping<int, YourClass> value in result) { foreach (YourClass obj in value) { //Some Code here } } 

And so, if you want to find something by the key

 List<YourClass> obj1 = result.Where(a => a.Key == 12).SingleOrDefault().Where(b=>b.objId.Equals(125)).ToList(); 

(In this case, the key is considered "int")

-2
source

All Articles