LINQ使用.ToDictionary而没有。选择

时间:2016-05-19 13:50:06

标签: c# .net linq

我有以下字典:

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值是第一个字典字符串的唯一lettersint值是通过数学公式计算的。

我有以下完美的工作:

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

1 个答案:

答案 0 :(得分:5)

这一点完全是多余的:

.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

相关问题