创建一个有条件的词典
本文关键字:有条件 一个 创建 | 更新日期: 2023-09-27 18:20:24
我有一个IEnumerable,其值如下:[1,2,6,8,10,5,6,9,4,2,6,8,2,7,9,2,4]我想创建一个字典,按照这个标准值进行分组
- x在1到3之间,并且正在计数
- x在4到7之间,并且正在计数
- x在8和10之间,并计数
我这样做是为了消除重复的值和计数
Dictionary<int, int> childDictionary = childArray.GroupBy(x => x)
.ToDictionary(g => g.Key,
g => g.Count());
结果:
key count
1 1
2 4
4 4
5 1
6 3
7 1
8 2
9 2
10 1
之后,可以在Dictionary中进行同样的操作,但有许多涉及GroupBy
的条件,如:
//Bad code
GroupBy(x>=1 and x<3)
我之前提到的所有条件?结果应该是这样的,假设它为每个条件取一个密钥
key count
1 5
2 9
3 5
其中:
- 1是第一个条件的关键
- 2是第二个条件的关键
- 3是第三个条件的关键
您应该在GroupBy中返回不同的键,例如使用不同的int值
using System;
using System.Linq;
var items = new int[] {1,2,6,8,10,5,6,9,4,4,2,6,8,2,4,7,9,2,4};
var result = items.GroupBy(x => {
//x between 1 to 3, and counting.
if (x >= 1 && x <= 3) return 1;
//x between 4 to 7, and counting.
if (x >= 4 && x <= 7) return 2;
//x between 8 and 10, and counted.
if (x >= 8 && x <= 10) return 3;
//else
return 4;
}).ToDictionary(x => x.Key, x => x.Count());
foreach (var kv in result)
{
Console.WriteLine("Key = {0}, Value = {1}", kv.Key, kv.Value);
}
结果:
Key = 1, Value = 5
Key = 2, Value = 9
Key = 3, Value = 5
演示:https://dotnetfiddle.net/wIAlrj