[英]Can I streamline this LINQ query
我正在學習LINQ,我想知道是否可以簡化以下LINQ查詢...
現在我有兩個字符串,我解析連接的字符串來計算每個單詞的使用。 我想知道是否可以保留一個LINQ表達式,但不必復制from和let表達式中的string.Concat部分。
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)) };
您的查詢返回一個有點奇怪的結果集:
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
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.