2 回答
TA贡献1155条经验 获得超0个赞
不建议使用 3 个独立列表。创建类以存储类别
public class Category
{
public string Name { get; set; }
public int Score { get; set; }
public int Count { get; set; }
}
然后用类别填充列表
// In your method add a category to list
var categories = new List<Category>();
categories.Add(new Category {
Name = "Category1",
Score = 10,
Count = 3
});
使用 System.Linq 对类别进行排序
var sortedCategores = categories.OrderByDescending(x => x.Score).ThenByDescending(x => x.Count).ToList();
循环访问集合
foreach(var category in sortedCategores)
{
Console.WriteLine($"{category.Name} [Score: {category.Score}] [Count: {category.Count}]");
}
TA贡献1824条经验 获得超8个赞
可能最简单的方法是创建一个类来保存每个列表中的关联属性,而不是尝试管理一堆列表及其项的顺序。我们还可以重写此类的 ToString 方法,以便它输出您当前默认使用的格式化字符串:
class Category
{
public string Name { get; set; }
public int Count { get; set; }
public int Score { get; set; }
public override string ToString()
{
return $"{Name} [Score: {Score}] [Count: {Count}]";
}
}
然后,您可以创建此类型的单个列表,而不是三个不同的列表。下面是一个示例,它使用现有列表来填充新列表,但理想情况下,您可以修改向三个列表添加项的代码,而不是向单个列表添加新项。拥有此单个列表后,可以使用扩展方法 OrderBy(将最小的项目放在前面)或 OrderByDescending(将最大的项目放在第 一位)按您喜欢的任何属性(然后按任何其他属性)对其进行排序:CategorySystem.Linq
var items = new List<Category>();
// Create a list of items based off your three lists
// (this assumes that all three lists have the same count).
// Ideally, the list of Items would be built instead of the three other lists
for (int i = 0; i < categories.Count; i++)
{
items.Add(new Category
{
Name = categories[i],
Count = count[i],
Score = score[i]
});
}
// Now you can sort by any property, and then by any other property
// OrderBy will put smallest first, OrderByDescending will put largest first
items = items.OrderByDescending(item => item.Score)
.ThenByDescending(item => item.Count)
.ToList();
// Write each item to the console
items.ForEach(Console.WriteLine);
GetKeyFromUser("\nDone! Press any key to exit...");
输出

- 2 回答
- 0 关注
- 128 浏览
添加回答
举报
