C#从IList中选择元素 [英] C# select elements from IList

查看:233
本文介绍了C#从IList中选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的列表,的IList< O>
0 有一些性能,但是其中只有两个是相关的:日期病程

I have a list of objects, IList<O>. O has several properties but only two of them are relevant: Date and Duration.

我要拆分列表到只包含具有匹配的日期和时间属性的对象几个列表。

I want to "split" the list into several lists that contain only the objects that have matching Date and Duration Properties.

例如:


0- Date==1, Duration==7  
1- Date==1, Duration==7  
2- Date==2, Duration==7  
3- Date==2, Duration==7  
4- Date==2, Duration==14  
5- Date==2, Duration==14  

期望的结果(IList的< IList的< O>>):

Desired result (IList<IList<O>>):


0-  
 0- Date==1, Duration==7  
 1- Date==1, Duration==7  
1-  
 0- Date==2, Duration==7  
 1- Date==2, Duration==7  
2-  
 0- Date==2, Duration==14  
 1- Date==2, Duration==14  

我知道这可以与一些LINQ选择做,但我不知道如何。

I know this can be done with some LINQ selects but am not sure how.

推荐答案

您可以使用以下内容:

var query = 
    from item in list
    group item by new { item.Date, item.Duration } into g
    select g.toList();
var result = query.toList();

这将创建包含您想要组的属性一个匿名类。然后,它扩展了 IGrouping 原始类型的列表。该查询然后运行产生外列表

This creates an anonymous class with the properties that you want to group by. It then expands the IGrouping to a List of the original type. The query is then run to produce the outer List.

这篇关于C#从IList中选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆