c# Linq的学习

获得数组的相同数和个数

1             int[] nums = new int[5] { 1, 1, 3, 1, 3 };
2             var d = from n in nums group n by n into g select new { Key = g.Key, Count = g.Count() };
3             foreach (var n in d)
4             {
5                 Console.WriteLine(n.Key);//
6                 Console.WriteLine(n.Count);//个数
7             }
8             Console.ReadLine();

 

 List<card> cardList = new List<card>();
            cardList.Add(new card { id = 1,type=1});
            cardList.Add(new card { id = 1, type = 2 });
            cardList.Add(new card { id = 1, type =3 });
            cardList.Add(new card { id = 1, type = 4 });
            cardList.Add(new card { id = 2, type = 1 });
            cardList.Add(new card { id = 3, type = 1 });
            cardList.Add(new card { id = 3, type = 2 });
            cardList.Add(new card { id = 4, type = 2 });

            var result = from t in cardList group t by t.id into g where g.Count() > 0 select new { id = g.Key, type = string.Join(",", g.Select(x => x.type).Distinct()) };
            //var res = cardList.GroupBy(x => new { x.id, x.type }).Where(x => x.Count() > 0).SelectMany(x => x.ToList());
            foreach (var item in result)
            {
                Console.WriteLine("ok");
                //id=1,type="1,2,3,4"
                //id=2,type="1"
                //id=3,type="1,2"
                //id=4,type="2"
            }

  

 
posted @ 2014-03-14 10:59  kadajEvo  阅读(101)  评论(0)    收藏  举报