gpt4 book ai didi

c# - LINQ 使用 .ToDictionary 而不使用 .Select

转载 作者:行者123 更新时间:2023-11-30 14:50:12 25 4
gpt4 key购买 nike

我有以下字典:

Dictionary<string, string> clauses = new Dictionary<string, string>();

从句是这样的:

"A|B" - "some text"
"A|D|E" - "some text"
"G" - "some text"
"E|A" - "some text"
...

我想填充下面的字典:

Dictionary<string, int> columnsBitMap = new Dictionary<string, int>();

其中string值是第一个字典字符串的唯一字母int值是通过数学公式计算的。

我有以下完美运行的:

columnsBitMap = String.Join("|", clauses.Select(clause => clause).Select(clause => clause.Key)).Split('|')
.Distinct().OrderBy(column => column)
-- can I remove the next Select ?
.Select((column, index) => new KeyValuePair<string, int>(column, index))
.ToDictionary(column => column.Key, column => Convert.ToInt32(Math.Pow(2, column.Value)));

但我想知道是否可以简化删除 .Select 部分?


输出应该是这样的:

A 1
B 2
D 4
E 8
G 16

最佳答案

这一点完全是多余的:

.Select(clause => clause)

只需删除它,其余的应该可以正常工作。


我认为没有太多理由摆脱这部分

.Select((column, index) => new KeyValuePair<string, int>(column, index))

但是如果你反对使用 KeyValuePair<TKey,TValue>你可以让它成为一个匿名对象

.Select((column, index) => new{ Key = column, Value = index })

但差别不大。


我以稍微不同的方式处理了您的要求:

var result = clauses.SelectMany(clause => clause.Key.Split('|'))
.Distinct().OrderBy(column => column)
.Select((column, index) => new {Key=column,Value=index})
.ToDictionary(column => column.Key, column => Convert.ToInt32(Math.Pow(2, column.Value)));

您的测试用例的工作示例:http://rextester.com/PWC41147

关于c# - LINQ 使用 .ToDictionary 而不使用 .Select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37325275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com