2017-01-17 3 views
0

私はこのコードとその動作を正しく書いています。 LINQを使用してこれを行うより良い方法はありますか?私はリスト内の各要素の数をcでlinqを使って数えたいと思っています#

List<int> list = new List<int>() { 1, 2, 3, 1, 2, 3, 1, 2, 7, 2, 2 }; 

var distinctList = list.Distinct(); 

var listWithCount = distinctList.Select(q=>new { num=q, count = list.Count(number=>number==q) }); 

foreach(var number in listWithCount) 
{ 
    Console.WriteLine("num : " + number.num + " count : " + number.count); 
} 
+2

Worksingコードは、あなたがすべきおそらく、SOにオフトピック私の友人でありますcodereviewでこれを投稿してください。 – Ian

+2

あなたはGroupByで試すことができます。私はそれがlist.GroupBy(p => p).select(p => new(number = p.Key、count = p.Count())...またはこれに似ていると思う。 –

+0

thanx @AndreiNeagu – huzefa

答えて

4

あなたはToDictionaryと一緒GroupByを使用することができます。

List<int> list = new List<int>() { 1, 2, 3, 1, 2, 3, 1, 2, 7, 2, 2 }; 

Dictionary<int, int> counts = list.GroupBy(x => x) 
            .ToDictionary(k => k.Key, v => v.Count()); 
1

は、ここでは、必要最小限の変更です:

List<int> list = new List<int>() { 1, 2, 3, 1, 2, 3, 1, 2, 7, 2, 2 }; 

foreach (var number in list.GroupBy(x => x)) 
{ 
    Console.WriteLine("num : " + number.Key + " count : " + number.Count()); 
} 
関連する問題