2011-08-09 3 views
1

を合理化することができます各単語の使用。 1つのLINQ式を保持することは可能ですが、fromとlet式のstring.Concatセクションをレプリケートする必要はありません。は、私は今、私は2つの文字列を持っていると私はカウントするように連結された文字列を解析...</p> <p>を私はLINQを学んでいると私は次のLINQクエリを効率化することが可能であるかどうかを知りたい、このLINQクエリ

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

答えて

4

あなたのクエリは少し奇妙な結果セットを返します。

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

ありがとう、これは私が探していたものです。 –

関連する問題