星期五, 8月 11, 2017

[LINQ] 群組字串連結

用 LINQ 做到該筆記 [SQL] 群組字串連結 的效果,分別用
  • GroupBy + string.Join
  • GroupBy + Aggregate
來做到
namespace ConsolePractice
{
    class Program
    {
        static void Main(string[] args)
        {
            List<LeaveApply> Data = new List<LeaveApply>();
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 8), EmpName = "張三" });
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 8), EmpName = "李四" });
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 8), EmpName = "王五" });
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 9), EmpName = "王五" });
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 10), EmpName = "趙六" });
            Data.Add(new LeaveApply() { Date = new DateTime(2017, 8, 10), EmpName = "蔡七" });

            // 方法一:string.join
            var result = Data
                    .GroupBy(g => g.Date)
                    .Select(g => new
                    {
                        Date = g.Key,
                        Description = string.Join(",", g.Select(s => s.EmpName))
                    });
                        
            // 方法二:Aggregate
            var result = Data
                .GroupBy(g => g.Date)
                .Select(s => new
                {
                    Date = s.Key,
                    Description = s.Aggregate(string.Empty, (c, n) => c + (string.IsNullOrEmpty(c)?string.Empty:",")+ n.EmpName)
                });

            foreach (var i in result)
            {
                Console.WriteLine($"{i.Date.ToString("yyyy/MM/dd")} - {i.Description}");
            }
        }
    }

    public class LeaveApply
    {
        public DateTime Date { get; set; }
        public string EmpName { get; set; }
    }
}
[LINQ] 群組字串連結

沒有留言:

張貼留言