public class ConsolidatedChild
{
public string School { get; set; }
public string Friend { get; set; }
public string FavoriteColor { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public string School { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Friend { get; set; }
public string Mother { get; set; }
public string FavoriteColor { get; set; }
}
上記の 2 つのクラスを前提として、LINQ を使用して、School、Friend、FavoriteColor プロパティでグループ化されたリストからリストを作成したいと思います。これは LINQ で可能ですか?
プロパティは無視してください。コードは質問の解決のためだけに書かれています。
ベストアンサー1
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});