我可以简化这个LINQ查询吗?

本文关键字:查询 LINQ 我可以 | 更新日期: 2023-09-27 18:05:03

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

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

        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)) };

我可以简化这个LINQ查询吗?

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

TheWord         Occurrence
this            1
is              2
the             2
first           1
sentencethis    1
is              2
the             2
second          1
sentence        1

这是你想要的,还是你更喜欢这样的结果?

TheWord         Occurrence
this            2
is              2
the             2
first           1
sentence        2
second          1

要得到这些结果,你可以这样做:

var res = from word in sentence.Split()
                               .Concat(sentence2.Split())
          group word by word into g
          select new { TheWord = g.Key, Occurrence = g.Count() };

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

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
                                                    }));