iT邦幫忙

0

C# Linq 問題

  • 分享至 

  • xImage

 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

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
glj8989332
iT邦研究生 4 級 ‧ 2022-03-19 12:21:19
最佳解答

你要的是使用 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; } 

}
0

了解,我在研究看看,感謝


friday night funkin

我要發表回答

立即登入回答