LINQ GroupBy List<>

时间:2015-12-10 20:38:34

标签: c# linq list

我有一个简单的LINQ查询,它试图执行一个GroupBy,其中一个项目是List<string>.

var viewModel = reports
       .GroupBy(c => new { c.Id, c.PetList })
       .Select(g => new ArmReportModel
        {
            PetList = g.Key.PetList,
            Pets = g.Count()
        });

在此声明之前,我正在执行我的EF存储库方法,该方法最终调用一个方法来创建上面的PetList。

如果我从GroupBy()删除PetList,它会按预期工作。为了按List<string>类型分组,我必须做些什么吗?

1 个答案:

答案 0 :(得分:3)

我认为Id是一个标识符,因此具有相同c的任何两个Id实际上是相同的并且具有相同的PetList。因此,我们可以GroupBy Id并以另一种方式获取PetList

var viewModel = reports
  .GroupBy(c => c.Id)
  .Select(g => new ArmReportModel
  {
    PetList = g.First().PetList, // Might need FirstOrDefault() with some providers
    Pets = g.Count()
  });

除此之外,我首先要确保IEqualityComparer<T>GroupBy一起使用。如果提供者允许,那么没问题。否则我会从:

开始
reports.Select(c => new {c.Id, c.PetList}).AsEnumerable()

这将从提供​​程序检索到内存中所需的最小值,以便可以从该点开始使用linq-to-objects提供程序。

我需要能够为某些IEqualityComparer<T>定义T,所以我停止使用匿名类型:

private class IdAndList
{
  public int Id { get; set; }
  public List<string> PetList { get; set; }
}

private class ReportIdAndPetListComparer : IEqualityComparer<IdAndList>
{
  public bool Equals(IdAndList x, IdAndList y)
  {
    if (ReferenceEquals(x, y)) return true;
    if (x == null || y == null) return false;
    if (x.Id != y.Id) return false;
    if (x.PetList == null) return y.PetList == null;
    if (y.PetList == null) return false;
    int count = x.PetList.Count;
    if (y.PetList.Count != count) return false;
    for (int i = 0; i != count; ++i)
      if (x.PetList[i] != y.PetList[i]) return false;
    return true;
  }

  public int GetHashCode(IdAndList obj)
  {
    int hash = obj.Id;
    if (obj.PetList != null)
      foreach (string pet in obj.PetList)
        hash = hash * 31 + pet.GetHashCode();
    return hash;
  }
}

如果你知道不可能的话,可以删除一些null PetList的测试。

现在:

var viewModel = reports.Select(c => new IdAndList{c.Id, c.PetList}).AsEnumerable()
    .GroupBy(c => c, new ReportIdAndPetListComparer())
    .Select(g => new ArmReportModel
    {
        PetList = g.Key.PetList,
        Pets = g.Count()
    });

或者如果提供者无法处理构建IdAndPetList类型,那么:

var viewModel = reports.Select(c => new {c.Id, c.PetList})
    .AsEnumerable()
    .Select(c => new IdAndList{c.Id, c.PetList})
    .GroupBy(c => c, new ReportIdAndPetListComparer())
    .Select(g => new ArmReportModel
    {
        PetList = g.Key.PetList,
        Pets = g.Count()
    });