public class EduSubjectEntity {
public Guid UID { get; set; }
public string metaType { get; set; }
public string code { get; set; }
public string name { get; set; }
public Guid? parentUID { get; set; }
public string remark { get; set; }
public string curriculum { get; set; }
}
List<string> metas = new List<string>() {
Metas.EduSubject.Topic,
Metas.EduSubject.SubTopic,
Metas.EduSubject.knowledge,
};
Dictionary<string, List<EduSubjectEntity>> all =
db.EduSubjects.Where(o => metas.Contains(o.metaType))
.ToList()
.GroupBy(o => o.metaType)
.ToDictionary(x => x.Key, o => o.ToList())
如果我想要在 list 先 group by metaType Code 在 ToDictionary
你要的是使用 anonymous type 代入group by的參數
比如
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<EduSubjectEntity> db = new List<EduSubjectEntity>()
{
new EduSubjectEntity { metaType = "1", code = "A", name = "aa" },
new EduSubjectEntity { metaType = "1", code = "A", name = "bb" },
new EduSubjectEntity { metaType = "2", code = "A", name = "cc" },
new EduSubjectEntity { metaType = "2", code = "A", name = "dd" },
new EduSubjectEntity { metaType = "3", code = "B", name = "ee" }
};
var all =
db
.GroupBy(o => new { o.metaType, o.code })
.ToDictionary(x => x.Key, o => o.ToList());
foreach(var pair in all)
{
Console.WriteLine($"Current metaType and code : {pair.Key.metaType} {pair.Key.code}");
foreach(var item in pair.Value)
{
Console.WriteLine(item.name);
}
}
}
}
public class EduSubjectEntity {
public Guid UID { get; set; }
public string metaType { get; set; }
public string code { get; set; }
public string name { get; set; }
public Guid? parentUID { get; set; }
public string remark { get; set; }
public string curriculum { get; set; }
}