代码参考:
using System; using System.Collections.Generic; using System.Linq; namespace LinqGroupByDemp { class Dorm { public string Id { get; set; } public int NotNullBedNum { get; set; } public string DormName { get; set; } } class StuDorm { public string Id { get; set; } public string StuName { get; set; } public string DormId { get; set; } public int NotNullBedNum { get; set; } public string DormName { get; set; } } class Program { static void Main(string[] args) { List<Dorm> dorm = new List<Dorm> { new Dorm {Id="11",NotNullBedNum=4,DormName="N11"}, new Dorm {Id="22",NotNullBedNum=888,DormName="N22"}, new Dorm {Id="33",NotNullBedNum=2,DormName="N33"}, new Dorm {Id="44",NotNullBedNum=5,DormName="N44"}, new Dorm {Id="55",NotNullBedNum=888,DormName="N55"}, new Dorm {Id="66",NotNullBedNum=888,DormName="N66"}, new Dorm {Id="77",NotNullBedNum=888,DormName="N77"}, new Dorm {Id="88",NotNullBedNum=888,DormName="N88"}, new Dorm {Id="99",NotNullBedNum=888,DormName="N99"} }; List<StuDorm> stuDorm = new List<StuDorm> { new StuDorm {Id="1",StuName="张三",DormId="11",NotNullBedNum=4,DormName="N11"}, new StuDorm {Id="2",StuName="李四",DormId="11",NotNullBedNum=4,DormName="N11"}, new StuDorm {Id="3",StuName="王志",DormId="11",NotNullBedNum=4,DormName="N11"}, new StuDorm {Id="4",StuName="王大伟",DormId="33",NotNullBedNum=2,DormName="N33"}, new StuDorm {Id="5",StuName="张长为",DormId="44",NotNullBedNum=5,DormName="N44"}, new StuDorm {Id="6",StuName="高小军",DormId="44",NotNullBedNum=5,DormName="N44"}, new StuDorm {Id="7",StuName="汪小韩",DormId="11",NotNullBedNum=4,DormName="N11"}, new StuDorm {Id="8",StuName="刘坤",DormId="44",NotNullBedNum=5,DormName="N44"}, new StuDorm {Id="9",StuName="赵涛",DormId="33",NotNullBedNum=2,DormName="N33"}, new StuDorm {Id="10",StuName="党利",DormId="44",NotNullBedNum=5,DormName="N44"}, new StuDorm {Id="11",StuName="吴利",DormId="44",NotNullBedNum=5,DormName="N44"} }; var q = from dM in dorm join sD in stuDorm on dM.Id equals sD.DormId into g from o in g.DefaultIfEmpty(new StuDorm { Id = "00", StuName = "xx", DormId = "yy", NotNullBedNum = -1, DormName = "zz" }) select new { DormId = dM.Id, StuDormId=o.Id, NotNullBedNum = o.NotNullBedNum, DormName = dM.DormName }; foreach (var e in q) { Console.WriteLine("{0}------{1}---------{2}-----------{3}", e.DormId, e.StuDormId, e.NotNullBedNum, e.DormName); } var rr = from e in q where e.StuDormId != "00" group e by e.DormId into gg select new { DormId = gg.Key, NotNullBedNum = gg.Count() }; foreach (var ee in rr) { Console.WriteLine("{0}======{1}", ee.DormId, ee.NotNullBedNum); } var rrr = from e in q where e.StuDormId=="00" select new { DormId = e.DormId, NotNullBedNum =0 }; var a = rr.Union(rrr); foreach (var ee in a) { Console.WriteLine("{0}/////////////////////////////{1}", ee.DormId, ee.NotNullBedNum); } } } }
标签:StuName,C#,Demo,DormName,Linq,DormId,new,NotNullBedNum,Id From: https://www.cnblogs.com/exesoft/p/16800935.html