Can I streamline this LINQ query
I am learning LINQ and I want to know if it is possible to streamline the following LINQ query...
Right now I have two strings and I parse the concatenated string to count the use of each word. I want to know is it possible to keep one LINQ expression but not have to replicate the string.Concat section in the from and let expressions.
string sentence = "this is the first sentence";
string sentence2 = "this is the second sentence";
var res = from word in string.Concat(sentence, sentence2).Split()
开发者_C百科let combinedwords = string.Concat(sentence, sentence2).Split()
select new { TheWord = word, Occurance = combinedwords.Count(x => x.Equals(word)) };
Your query returns a slightly bizarre resultset:
TheWord Occurrence
this 1
is 2
the 2
first 1
sentencethis 1
is 2
the 2
second 1
sentence 1
Is that what you want, or would you you prefer the results to be more like this?
TheWord Occurrence
this 2
is 2
the 2
first 1
sentence 2
second 1
To get these results you can do something like this:
var res = from word in sentence.Split()
.Concat(sentence2.Split())
group word by word into g
select new { TheWord = g.Key, Occurrence = g.Count() };
Another option; better (theoretical) performance but less readable:
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
}));
精彩评论