using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqTip
{
class Program
{
public enum Teams
{
Valor, Mystic, Instinct, Dark
}
public class Trainer
{
public Teams Team;
public string Name;
public Trainer(Teams team, string name)
{
Team = team; Name = name;
}
}
static void Main(string[] args)
{
//來源資料如下
List<Trainer> trainers = new List<Trainer>()
{
new Trainer(Teams.Valor, "Candela"),
new Trainer(Teams.Valor, "Bob"),
new Trainer(Teams.Mystic, "Blanche"),
new Trainer(Teams.Valor, "Alice"),
new Trainer(Teams.Instinct, "Spark"),
new Trainer(Teams.Mystic, "Tom"),
new Trainer(Teams.Dark, "Jeffrey")
};
//目標:以Team分類,將同隊的訓練師集合成List<Trainer>,
//最終產出Dictionary<Teams, List<Trainer>>
//以前的寫法,跑迴圈加邏輯比對
var res1 = new Dictionary<Teams, List<Trainer>>();
foreach (var t in trainers)
{
if (!res1.ContainsKey(t.Team))
res1.Add(t.Team, new List<Trainer>());
res1[t.Team].Add(t);
}
//新寫法,使用LINQ GroupBy
var res2 =
trainers.GroupBy(o => o.Team)
.ToDictionary(o => o.Key, o => o.ToList());
}
}
}