[C#] 如何groupby list<[自訂class]> 資料?

  • 42
  • 0
  • C#
  • 2023-12-29

[C#] 如何groupby?

以下程式片段:

//Program.cs

static void Main(string[] args)
{

	List<Class_tbl> myTbl;

	myTbl= new List<Class_tbl>();
	myTbl.Add(new Class_tbl{ Id = 1, School = "highSchool", 班別 = "甲", Name = "A"});
	myTbl.Add(new Class_tbl{ Id = 2, School = "highSchool", 班別 = "甲", Name = "B"});
	myTbl.Add(new Class_tbl{ Id = 3, School = "highSchool", 班別 = "甲", Name = "C"});
	
	//這邊判斷式自己發揮
	foreach (var y in myTbl)
	{
		if(y.Id == 1)
		{
			y.listPort.Add("事蹟a");

		}

		else if(y.Id == 2)
		{
			y.listPort.Add("事蹟b");
			y.listPort.Add("事蹟c");

		}

		else if(y.Id == 3)
		{
			y.listPort.Add("事蹟d");
			y.listPort.Add("事蹟e");
			y.listPort.Add("事蹟f");

		}
	}

	var groupBy_tbl = from tbl in myTbl
	group tbl by new {tbl.班別, tbl.Name } into grouped
	select new 
	{
		班別 = grouped.Key.班別 ,
		Name = grouped.Key.Name ,
		count = grouped.Sum(tbl => tbl.listPort.Count)
	};

	//print
	Console.WriteLine("班別 ,Name ,事蹟數");
	foreach (var x in groupBy_tbl)
	{
		if (x.count > 0)
			Console.WriteLine(x.班別 + "," + x.Name + "," + x.count);
	}
	
	//result
	//班別 ,Name ,事蹟數
	//甲, A, 1
	//甲, B, 2
	//甲, C, 3
}

internal class Class_tbl
{
	public int Id { get; set; }
	public string School { get; set; }
	public string 班別 { get; set; }
	public string Name { get; set; }
	public List<string> list事蹟 { get; set; }

	public Class_tbl()
	{
		list事蹟 = new List<string>();
	}
}