5

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

I have the following:

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

And I now wish to iterate through each collection and retrieve the purchase histories for that user (and check if some stuff exists in the collection of purchase histories).

halfer
  • 19,824
  • 17
  • 99
  • 186
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

3 Answers3

6

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 statement

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);
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • Instead of doing a 2nd loop - is there a way to check if the a PurchaseHistory exists which has a ... i donno .. `item.PurchasedOn > someDate` ? – Pure.Krome Aug 26 '15 at 12:42
  • Hmm - i tried that ... AH! i tried results.Any(...) .. ooops! it's on the `group.Any(..)`. ta. got it. – Pure.Krome Aug 26 '15 at 12:52
0

Calling..

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

With..

bool SomeStuffExists(PurchaseHistory item)
{
    return ..
}

Yields tuples in the likes of..

  • ("UserNameX", true)
  • ("UserNameY", false)
  • ..
-2

This is the way if you want to iterate through all the items

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

And this is the way if you want to search some thing by key

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

(Key is considered as 'int' in this case)

Lali
  • 2,816
  • 4
  • 30
  • 47