日期:2014-05-20  浏览次数:21063 次

Linq中如何取出每个用户的符合条件的第一条记录?
Linq中如何取出每个用户的符合条件的第一条记录?

数据库有以下几个字段:
主键     用户id       名次       时间                       是否正常
1           100             10             20101012                   1
2           100             20             20101009                   1
3           200             11             20101011                   1
4           100             18             20101008                   1
5           300             2               20101010                   1
6           300             15             20101013                   1
7           300             16             20101002                   0
我要得到这样的结果:
100       18         20101008
200       11         20101011
300       2           20101010
请问这个用Linq怎么实现??

------解决方案--------------------
根据时间排序
 db.Tb
.OrderByDescending(x=> x.时间) 
.group ...
.FirstOrDefault();
------解决方案--------------------
什么条件啊??
------解决方案--------------------
C# code

  static void Main(string[] args)
        {
            var list = GetData();

            var query =
                    from u in list
                    where u.IsNormal == "1"
                    group u by u.UserId into g
                    orderby g.Key
                    from u2 in g
                    where u2.Date == g.Min(u3 => u3.Date)
                    select u2;

            foreach (var u in query)
                Console.WriteLine("{0}, {1}, {2}", u.UserId, u.Date, u.Rank);
            

            Console.Read();
        }

        static IEnumerable<User> GetData()
        {
            yield return new User { UserId = "100", Rank = "10", Date = "20101012", IsNormal = "1" };
            yield return new User { UserId = "100", Rank = "20", Date = "20101009", IsNormal = "1" };
            yield return new User { UserId = "200", Rank = "11", Date = "20101011", IsNormal = "1" };
            yield return new User { UserId = "100", Rank = "18", Date = "20101008", IsNormal = "1" };
            yield return new User { UserId = "300", Rank = "2", Date = "20101010", IsNormal = "1" };
            yield return new User { UserId = "300", Rank = "15", Date = "20101013", IsNormal = "1" };
            yield return new User { UserId = "300", Rank = "16", Date = "20101002", IsNormal = "0" };
        }