我怎样才能通过键 return 来自 .NET IGrouping 的值?

How can I return the Value from a .NET IGrouping via a Key?

我正在努力弄清楚如何检索 IGrouping 实例的 Value 部分。

我有以下内容:

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

我现在希望遍历每个集合并检索该用户的购买历史记录(并检查购买历史集合中是否存在某些东西)。

嵌套循环怎么样?

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

foreach (IGrouping<string, PurchaseHistory> group in results)
{
    foreach (PurchaseHistory item in group)
    {
        CheckforStuff(item);
    }
}

或一个带 linq 语句的循环

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);
}

如果你想遍历所有项目,这就是方法

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

如果你想按键搜索某些东西,这就是方法

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

(在这种情况下,密钥被视为 'int')

打电话..

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

有..

bool SomeStuffExists(PurchaseHistory item)
{
    return ..
}

生成类似...的元组

  • ("UserNameX", 真)
  • ("UserNameY", 假)
  • ..