【问题标题】:Counting occurrences of the first x elements of sublist in all sublists of the jagged list计算锯齿状列表的所有子列表中子列表的前 x 个元素的出现次数
【发布时间】:2016-05-06 11:21:49
【问题描述】:

我有一个空字典:

Dictionary<List<string>, int> occurrences = new Dictionary<List<string>, int>();

这是我的锯齿状列表:

List<List<string>> jaggedList = new List<List<string>>();

x 是我将要在锯齿状列表中计数的第一个元素的数量。在这个例子中:

x=2;

但我希望它在我得到比 x+1 更“厚”的子列表时自行更改

锯齿状列表:

{ cc kk ww }
{ cc kk aa }
{ cc oo ll }
{ cc jj oo }
{ ww oo kk }
{ ww oo gg }
{ ww gg kk }
{ kk ll oo }
{ ll kk nn }
{ mm nn oo }
{ mm nn jj }

我对 LINQ 完全没有希望,所以我自己做不到。我希望我的occurrences 字典在TKey 中分组x 索引元素,并且它在TValue 中的出现计数,因此结果如下所示:

Keys:     Values:
{ cc kk }   2  //because those appear together in this order in 2 sublist(s)
{ cc oo }   1  //because those appear together in this order in 1 sublist(s)
{ cc jj }   1  //et cetera
{ ww oo }   2
{ ww gg }   1
{ kk ll }   1  //<-note that those do not appear in this order twice
{ ll kk }   1  
{ mm nn }   2  

作为提示,我也有一个 linq 命令可以执行相同的操作,但不是使用字符串列表而是使用常规字符串:

我所说的字符串:

List<string> list = new List<string>();

{ gg }
{ gg }
{ jj }
{ ww }
{ ww }
{ jj }
{ mm } 
{ ww }
{ ll }
{ kk }
{ ll }

Linq 命令:

var dic = list.GroupBy(b => b).ToDictionary(group => group.Key, group => group.Count());

字典:

Dictionary<string, int> otherOccurrences = dic;

结果:

Keys:     Values:
{ gg }      2      //because it appears in this list 2 time(s)
{ jj }      2      //same with this one
{ ww }      3      //et cetera
{ mm }      1
{ ll }      2
{ kk }      1

我非常感谢在编辑指定的linq 命令以获得与我的occurrences 类似的命令的帮助。如果我在某个地方错了,请随时纠正我。如果我没有说清楚,我很抱歉,如果您不明白,请随时询问,以便我更具体地解释。

【问题讨论】:

  • 试试这个jaggedList.GroupBy(lst =&gt; string.Join("", lst.Take(x))) .ToDictionary(el =&gt; el.Key, el =&gt; el.Count());
  • 我检查了几次你的解决方案,结果你这样做就像我的列表是 Dictionary 出现次数 = new Dictionary();而不是 Dictionary, int> 出现 = new Dictionary, int>();我不想将 x 个元素连接成一个,而是将 x 个元素连接成一个列表。你能再帮我解决一下吗?
  • 这可能是我的错,将左侧有列表的损坏声明放在右侧,字符串放在右侧。对不起。
  • 我看到你设法解决了你的问题,你可以发布你的解决方案作为答案。

标签: c# linq list jagged-arrays


【解决方案1】:

要解决的主要问题是平等。两个“相同”的列表不相等。即使它们包含相同的元素,它们仍然是不同的对象。您必须为GroupBy 函数提供IEqualityComparer

var n = 2;
var dic = list.Select(l => l.Take(n))
              .GroupBy(b => b, new IEnumerableComparer<string>())
              .ToDictionary(group => group.Key, group => group.Count());

IEnumerableComparer 按内容比较列表。可以有很多方法来实现它。一个不错的例子在这里:IEqualityComparer for SequenceEqual

【讨论】:

  • 我宁愿像@tchelidze 那样做,除了他犯了一个我刚刚注意到的错误。他这样做就像我的字典将字符串作为键一样,因此他将 x 元素连接成一个元素,而不是像字面上将 x 元素添加为列表一样,就像声明了我的字典一样 (Dictionary, int> 出现次数 = new Dictionary, int>();)
猜你喜欢
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 2013-12-02
  • 2020-06-09
相关资源
最近更新 更多