根据属性将列表分成多个列表

时间:2013-06-08 09:50:25

标签: c#

我有一个List包含接口IGrid的项目(我创建了它)

public interface IGrid
{
   RowIndex { get; set; }
   ColumnIndex { get; set; }
}

我想创建一种方法,将列表分隔为多个列表列表>

基于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;
     }
}

有什么更好的方法可以做到这一点?

1 个答案:

答案 0 :(得分:5)

是的,您可以在一个声明中使用LINQ来完成它:

public List<List<IGrid>> Separat(List<IGrid> source) {
    return source
        .GroupBy(s => s.RowIndex)
        .OrderBy(g => g.Key)
        .Select(g => g.ToList())
        .ToList();
}

如果您不关心列表以RowIndex的升序出现,即方法生成它们的方式,则可以从方法调用链中删除OrderBy方法调用。 / p>