如何在iccollections中使用GroupBy



我使用GroupBy对对象进行分组,如:

var categories=
    tovRDb.MyObjects.AsEnumerable().Where(t => myHashSet.Contains(t.Id))
                      .GroupBy(t => t.Specialization, t => t,
                               (key, g) => new {Name = key.Name, CategoryItems = g.ToList()})
                      .OrderBy(t => string.IsNullOrEmpty(t.Name))
                      .ThenBy(t => t.Name)
                      .ToList();

它工作得很好。
但是现在我想分组对象,其中特殊化是ICollection<>。
例如:

MyObject1: "Berlay's Meat"
Specializations{Chicken, Pork, Beef}
MyObject2: "Wonday's Chickery"
Specializations{Chicken}

MyObject3: "Rooki's Meat"
Specializations{Chicken, Pork}

和group by后:

Pork{MyObject1: "Berlay's Meat",MyObject3: "Rooki's Meat"}
Beef{MyObject1: "Berlay's Meat"}
Chicken{MyObject1: "Berlay's Meat",MyObject2: "Wonday's Chickery", MyObject3: "Rooki's Meat"}

有什么建议吗?

With categories as:

var categories = tovRDb.MyObjects.AsEnumerable().Where(t => myHashSet.Contains(t.Id));
var catsGrouped = categories.SelectMany(
    x => x.Specializations, // Specializations is an IEnumerable<Specialization>
    (x, y) => new
    {
        Category = x,
        Specialization = y,
    }).GroupBy(x => x.Specialization, x => x.Category)
    .ToArray();

我使用SelectMany将每个类别的专门化"相乘"…然后我用Specialization重新组合结果。结果是IGrouping<Specialization, MyObject>[]

相关内容

  • 没有找到相关文章

最新更新