日期:2014-05-17  浏览次数:20703 次

求助一个lambda表达式的写法: groupby分离部分数据
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;

namespace Leaf
{
    public class Test5
    {
        public static void Main(string[] args)
        {
            List<DbInfo> list = new List<DbInfo>()
            {
                new DbInfo(){ DbId=1,HostId=1 },    
                new DbInfo(){ DbId=2,HostId=1 },
                new DbInfo(){ DbId=3,HostId=2 },
                new DbInfo(){ DbId=4,HostId=2 }
            };

            //todo: 如何将list中的对象,group by HostId, 每个HostId保留一条记录? (不要用循环)
            //如上面的list, 最终结果会保留 DbId = 1 和 3
           

            Console.ReadLine();
        }
    }

    public class DbInfo
    {
        public long DbId { get; set; }
        public long HostId { get; set; }
    }
}
lambda

------解决方案--------------------
var selected = list.GroupBy(v => v.HostId).Select(it => it.First()).ToList();
            //selected.ForEach(v => Console.WriteLine(v.DbId));

------解决方案--------------------
var selected1 = from dbinfo in list
                            group dbinfo by dbinfo.HostId into list2
                            select new
                       &n