首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我是否可以简化此LINQ查询

我是否可以简化此LINQ查询
EN

Stack Overflow用户
提问于 2011-08-09 23:03:53
回答 1查看 118关注 0票数 1

我正在学习LINQ,我想知道是否有可能简化以下LINQ查询...

现在我有两个字符串,我解析连接的字符串来计算每个单词的用法。我想知道是否有可能保留一个LINQ表达式,而不必在from和let表达式中复制string.Concat部分。

代码语言:javascript
复制
        string sentence = "this is the first sentence";
        string sentence2 = "this is the second sentence";

        var res = from word in string.Concat(sentence, sentence2).Split()
                  let combinedwords = string.Concat(sentence, sentence2).Split()
                  select new { TheWord = word, Occurance = combinedwords.Count(x => x.Equals(word)) };
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-09 23:27:11

您的查询返回一个有点奇怪的结果集:

代码语言:javascript
复制
TheWord         Occurrence
this            1
is              2
the             2
first           1
sentencethis    1
is              2
the             2
second          1
sentence        1

这是你想要的吗,还是你希望结果更像这样?

代码语言:javascript
复制
TheWord         Occurrence
this            2
is              2
the             2
first           1
sentence        2
second          1

要获得这些结果,您可以执行以下操作:

代码语言:javascript
复制
var res = from word in sentence.Split()
                               .Concat(sentence2.Split())
          group word by word into g
          select new { TheWord = g.Key, Occurrence = g.Count() };

另一种选择;更好的(理论上)性能,但可读性较差:

代码语言:javascript
复制
var res = sentence.Split()
                  .Concat(sentence2.Split())
                  .Aggregate(new Dictionary<string, int>(),
                             (a, x) => {
                                           int count;
                                           a.TryGetValue(x, out count);
                                           a[x] = count + 1;
                                           return a;
                                       },
                             a => a.Select(x => new {
                                                        TheWord = x.Key,
                                                        Occurrence = x.Value
                                                    }));
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6998352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档