我有一个包含4个列表的嵌套列表。
ListOflist has: list[0] contains Id
list[1] contains power values
list[2] contains count values.
我正在尝试使用此函数按升序对列表进行排序:
bool ascending = true; // ascending
int mult = ascending ? 1 : -1;
listoflist.Sort((a, b) => mult * a[2].CompareTo(b[2]));
目标是根据计数值排列列表列表,这意味着字段2。当我尝试在排序后显示列表列表时,列表[0]不包含ID而是包含不同的值,并且嵌套列表中列表的顺序已更改。
你知道我犯的错误是什么吗?
这是因为你实际上是值而不是对象 - 尝试使用自定义对象:
class Data
{
public string Id { get; set; }
public long Power { get; set; }
public int Count { get; set; }
}
var listoflist = new List<Data>
{
new Data {Id = "#1", Power = 2, Count = 10},
new Data {Id = "#2", Power = 3, Count = 2},
new Data {Id = "#3", Power = 4, Count = 5}
};
var ascending = true; // ascending
var mult = ascending ? 1 : -1;
listoflist.Sort((a, b) => mult * a.Count.CompareTo(b.Count));
我不知道为什么你使用列表列表而不是对象列表,但在你的情况下你可以使用LINQ(尽管它在内存中添加了一个额外的List <>实例)
bool ascending = true;
if (ascending)
listoflist= listoflist.OrderBy(l => l[2]).ToList();
else
listoflist = listoflist.OrderByDescending(l => l[2]).ToList();