我有一个List包含接口项IGrid(我创建了它)
public interface IGrid
{
RowIndex { get; set; }
ColumnIndex { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个方法将List分成多个列表List>
基于RowIndex属性
所以我写道:
public List<List<IGrid>> Separat(List<IGrid> source)
{
List<List<IGrid>> grid = new List<List<IGrid>>();
int max= source.Max(c => c.RowIndex);
int min = source.Min(c => c.RowIndex);
for (int i = min; i <= max; i++)
{
var item = source.Where(c => c.RowIndex == i).ToList();
if (item.Count > 0)
grid.Add(item);
}
return grid;
}
}
Run Code Online (Sandbox Code Playgroud)
有什么更好的方法呢?
Yes, you can do it with LINQ in a single statement:
public List<List<IGrid>> Separat(List<IGrid> source) {
return source
.GroupBy(s => s.RowIndex)
.OrderBy(g => g.Key)
.Select(g => g.ToList())
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
If you do not care that the lists appear in the ascending order of RowIndex, the way that your method produces them, you can remove the OrderBy method call from the chain of method invocations.
| 归档时间: |
|
| 查看次数: |
2249 次 |
| 最近记录: |