如何订购groupBy项目

时间:2016-10-30 13:15:59

标签: c# linq

使用此Linq查询返回4 DateTime的分组:

IEnumerable<IGrouping<DateTime, QuoteSnapshotModel>> lista = (from q in quoteModeList
                                                              where q.QuoteTradeType == "Q"
                                                              select q).GroupBy(n => n.ExceriseDate);

如何按DateTime订购群组并仅获取第一组? 意思是**List<QuoteSnapshotModel>**

另外,我怎样才能获得第二个List<QuoteSnapshotModel>(根据DateTime

3 个答案:

答案 0 :(得分:0)

  

如何按DateTime订购论坛

.OrderBy(g => g.Key).OrderBy(g => g.First().ExerciseDate)

  

只获得第一组?

.First()(或.FirstOrDefault(),如果可能有0组)

  

如何才能获得第二个List(根据DateTime)

.Skip(1).Take(1).ElementAt(1).Skip(1).First()

全部放在一起:

IEnumerable<IGrouping<DateTime, QuoteSnapshotModel>> lista = ( 
    from q in quoteModeList
    where q.QuoteTradeType == "Q"
    select q
).GroupBy(n => n.ExerciseDate);

IList<QuoteSnapshotModel> firstQuote = lista.OrderBy(x => x.Key).Select(x => x.ToList()).FirstOrDefault();
IList<QuoteSnapshotModel> secondQuote = lista.OrderBy(x => x.Key).Skip(1).Select(x => x.ToList()).FirstOrDefault(); 

答案 1 :(得分:0)

<强>更新

您只能使用第一组

List<QuoteSnapshotModel> list =quoteModeList.Where(x=>x.QuoteTradeType =="Q")
                                            .GroupBy(x => x.ExceriseDate)
                                            .OrderBy(x=>x.Key)
                                            .FirstOrDefault().Select(x=>x.QuoteTradeType).ToList();

您只能使用第二组

 List<QuoteSnapshotModel> list =quoteModeList.Where(x=>x.QuoteTradeType =="Q")
                                             .GroupBy(x => x.ExceriseDate)
                                             .OrderBy(x=>x.Key)
                                             .Skip(1).First().Select(x=>x.QuoteTradeType).ToList()

答案 2 :(得分:0)

试试这个:

为此你必须创建一个list<QuoteSnapshotModel&gt;在班级QuoteSnapshotModel内。

int record = 1;
   List<QuoteSnapshotModel> result =
                 quoteModeList
                .Where(x => x.QuoteTradeType == "Q")
                .GroupBy(x => x.ExceriseDate,
                (a, b) => new QuoteSnapshotModel
                {
                    ExceriseDate = a,
                    ListQuoteSnapshotModel = b.ToList()
                })
                .OrderByDescending(t => t.ExceriseDate)
                .Skip(record - 1).Take(1).ToList();