linq group by应用一

目标:1、设ID, ID1,ID2 为属性组合,若此属性组合值唯一时查询该单条记录value值;若不唯一时,获取该多条记录中collecttime时间最小的记录value值

测试代码

    class Person
    {        
        public Person() { }
        public string ID { get; set; }
        public string ID1 { get; set; }
        public string Caption { get; set; }
        public string ID2 { get; set; }
        public int Value { get; set; }
        public DateTime CollectTime { get; set; }
    }
            List<Person> persons = new List<Person>();
            Person person1 = new Person();
            person1.ID = "1";
            person1.ID1 = "A";
            person1.ID2 = "A1";
            person1.Value = 22;
            person1.CollectTime = new DateTime(2011, 11, 11);
            persons.Add(person1);
            Person person2 = new Person();
            person2.ID = "2";
            person2.ID1 = "B";
            person2.ID2 = "B1";
            person2.Value = 33;
            person2.CollectTime = new DateTime(2011, 12, 11);
            persons.Add(person2);
            Person person3 = new Person();
            person3.ID = "1";
            person3.ID1 = "C";
            person3.ID2 = "C1";
            person3.Value = 22;
            person3.CollectTime = new DateTime(2013, 11, 11);
            persons.Add(person3); 
            Person person4= new Person();
            person4.ID = "1";
            person4.ID1 = "C";
            person4.ID2 = "C1";
            person4.Value = 22;
            person4.CollectTime = new DateTime(2012, 11, 11);
            persons.Add(person4);
            var query = from c in persons
                        orderby c.CollectTime
                        group c by new { id = c.ID, id1 = c.ID1, id2 = c.ID2 } into r
                        select r;
            foreach (var group in query)
            {
                //输出分组依据的字段 
                Console.WriteLine(group.Key);

                Console.WriteLine(group.First());
                // 输出组内成员 
                //foreach (var score in group)
                //{
                //    Console.WriteLine(score);
                //}
            } 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值