私はlinqクエリを持っています
var x = (from t in types select t).GroupBy(g =>g.Type)
その結果、グループ化されたすべてのオブジェクトとその数を含む単一の新しいオブジェクトが必要になります。このようなもの:
type1, 30
type2, 43
type3, 72
より明確にするために: グループ化の結果は、項目タイプごとのオブジェクトではなく、1 つのオブジェクトにする必要があります
読む:その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());
ここでの答えは私を近づけましたが、2016 年には次の LINQ を書くことができました。
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
グループ化されたすべてのオブジェクト、またはすべてのタイプ? あなたが望むかもしれないように聞こえます:
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());
ペアを選択して辞書を作成する必要はありません。
var x = from t in types
group t by t.Type into grouped
select new { type = grouped.Key,
count = grouped.Count() };
各タイプでルックアップを実行してその頻度を取得できるようにする場合は、列挙を辞書に変換する必要があります。
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)]);