2012-02-18 15 views
3

2つのlinq式を1つに結合する方法はありますか?私。 1つのLINQ式はDistCountとNormCountの両方を2つの別個のint変数に返します。1つのLINQ式の中の個数と個体数

DistCount = (from string row in myList[i] 
       where row.Length > 0 
       select row).Distinct().Count(); 

NormCount = (from string row in myList[i] 
       where row.Length > 0 
       select row).Count(); 
+0

'VAR最終=新しい{DISTCOUNT = 1、NormCount = 2};' –

答えて

4

は、行によってgroupを行います。次に、あなたの質問に答えるために個別のカウント数(グループの#)との合計(Count秒の合計)

var q = (from string row in myList[i] 
    where row.Length > 0 
    group row by row into rowCount 
    select new {rowCount.Key, rowCount.Count}) 

int distinct = q.Count(); 
int total = q.Sum(r=>r.Count); 
+0

コードの意図を隠す種類は、別名を付けて別のメソッドに入れる必要がありますまたはコメントしました。パフォーマンスも疑問です。 –

+0

qの最後に "ToList"を覚えていれば、グループ全体を2回行うことになります – Cine

0

あなたは匿名型を選択してみてください:

from string row in myList[i] 
where row.Length > 0 
select new { 
    DistCount = row.Distinct().Count(), 
    NormCount = row.Count() 
} 
+0

Count()は、著者が必要とする文字列ではなく文字列の文字の数を数えます。 –

4

を持っています。これには組み込みのlinq式はありません。

サイドノート。本当に必要な場合は作成することができます。

名前の戻り値の型をTupleではなく作成して、使いやすくすることができます。

使用例のようになります。

var distinctAndCount = (from string row in myList[i] 
           where row.Length > 0 
           select row 
          ).DistinctAndCount(); 

または私が個人的にそれを書くことを好むだろうとして:

var distinctAndCount = myList[i].Where(row => row.Length > 0).DistinctAndCount(); 
関連する問題