ToDictionary按List分组

ToDictionary按List分组

本文介绍了使用GroupBy / ToDictionary按List分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello C#gurus和mavens。我有一个问题,我认为其实际上是 .GROUPBY()问题。



我有一组类型为细胞的。每个单元格都有一个属性 Candidates ,它是一个有序的字符串列表:

Hello C# gurus and mavens. I have a question for you which I believe is actually a .GROUPBY() question.

I have a set of objects of type Cell. Each Cell has a property Candidates which is an ordered list of strings:

public List<string> Candidates { get; private set; }





我想用他们共同的候选人对 Cell 进行分组(例如所有细胞在一组中有候选人{x,y,z},在另一组中有{x,z}的那些,等等) 。



我的编码类似于以下内容:





I would like to group the Cells by their common Candidates (e.g. all Cells with candidates {"x", "y", "z"} in one group, those with {"x", "z"} into another, etc).

I coded something similar to the following:

cellGroupings =
  allCells.Where(c => c.Candidates.Count > 0)
          ,GroupBy(c.Candidates)
          .ToDictionary(g => g.Key, g => g);





所以让我们来吧假设allCells有一些单元格集:



So lets assume allCells has some set of cells:

{ Cell.Name = "1st", Cell.Candidates = { "x", "y", "z" } }
{ Cell.Name = "2nd", Cell.Candidates = { "x", "z" }      }
{ Cell.Name = "3rd", Cell.Candidates = { "x", "z" }      }
{ Cell.Name = "4th", Cell.Candidates = { "x", "y", "z" } }





问题在于 GroupBy()和/或 ToDictionary()似乎将每个候选列表视为与其他列表不相等,尽管它们具有相同的候选者 。因此,而不是上面生成两个分组(一个用于{x,y,z}一个包含1st和4th,一个用于{x,z}包含2nd 和3rd)它生成四个分组,每个分组1个单元



是否有一些技巧可以使两个列表看起来相当于 GroupBy()和/或 ToDictionary()



The problem is that GroupBy() and/or ToDictionary() seems to be treating each list of candidates as not-equivalent to the other lists, despite them having the same Candidates. So, instead of the above generating two groupings (one for { "x", "y", "z" } a containing "1st" and "4th", and one for { "x", "z" } containing "2nd" and "3rd") it generates four groupings with 1 Cell each.

Is there some trick to getting two lists to appear equivalent to GroupBy() and/or ToDictionary()?

推荐答案

var cellGroupings = allCells.Where(c => c.Candidates.Any()).GroupBy(c => String.Join(",", c.Candidates.ToArray())).ToDictionary(g=>g.Key, g=>g);





希望它有所帮助!



Hope it helps!


这篇关于使用GroupBy / ToDictionary按List分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:53