45

私はlinqクエリを持っています

var x = (from t in types select t).GroupBy(g =>g.Type)

その結果、グループ化されたすべてのオブジェクトとその数を含む単一の新しいオブジェクトが必要になります。このようなもの:

type1, 30    
type2, 43    
type3, 72

より明確にするために: グループ化の結果は、項目タイプごとのオブジェクトではなく、1 つのオブジェクトにする必要があります

4

6 に答える 6

48

読む:そのLINQの101 LINQサンプル-Microsoft MSDNサイトのグループ化演算子

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

forsingle オブジェクトは stringbuilder を利用し、それを追加するか、これを辞書の形式に変換します

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   
于 2012-05-25T07:25:51.673 に答える
48

ここでの答えは私を近づけましたが、2016 年には次の LINQ を書くことができました。

List<ObjectType> objectList = similarTypeList.Select(o =>
    new ObjectType
    {
        PropertyOne = o.PropertyOne,
        PropertyTwo = o.PropertyTwo,
        PropertyThree = o.PropertyThree
    }).ToList();
于 2016-03-24T17:56:07.297 に答える
39

グループ化されたすべてのオブジェクト、またはすべてのタイプ? あなたが望むかもしれないように聞こえます:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

編集:辞書に入れたい場合は、次を使用できます:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

ペアを選択して辞書を作成する必要はありません。

于 2012-05-25T07:25:01.567 に答える
3
var x = from t in types
        group t by t.Type into grouped
        select new { type = grouped.Key,
                     count = grouped.Count() };
于 2012-05-25T07:28:32.807 に答える
1

各タイプでルックアップを実行してその頻度を取得できるようにする場合は、列挙を辞書に変換する必要があります。

var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
        .GroupBy(type => type)
        .ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
    Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);
于 2012-05-25T07:41:38.187 に答える