猿问

按两个不同的列表对列表进行排序

我正在尝试按类别对一些数据进行排序。每个类别都有一个计数,或类别中的条目数量和我给该类别的分数。分数是最重要的,在排序时应始终首先考虑。计数不如分数重要,但仍然很重要,在排序时应将其视为第二位。


List<string> categories = new List<string>();

List<int> count = new List<int>();

List<int> score = new List<int>();


categories.Add("category1");

count.Add(23);

score.Add(8);

...

for(int i = 0; i < sortedcategories.Count; i++) {

    Console.WriteLine(sortedCategories[i] + sortedScore[i] + sortedCount[i]);

}

// Should Output

/*

category8 [Score: 10] [Count: 8]

category2 [Score: 10] [Count: 5]

category1 [Score: 8] [Count: 23]

category5 [Score: 7] [Count: 12]

category4 [Score: 5] [Count: 28]

category3 [Score: 5] [Count: 25]

category7 [Score: 5] [Count: 17]

category6 [Score: 2] [Count: 34]

*/

如何执行排序操作,为我提供上述输出?(如果这更容易与数组,我也可以使用数组)


www说
浏览 155回答 2
2回答

白衣非少年

不建议使用 3 个独立列表。创建类以存储类别public class Category&nbsp;{&nbsp; &nbsp; &nbsp;public string Name { get; set; }&nbsp; &nbsp; &nbsp;public int Score { get; set; }&nbsp; &nbsp; &nbsp;public int Count { get; set; }}然后用类别填充列表// In your method add a category to listvar categories = new List<Category>();categories.Add(new Category {&nbsp; &nbsp; &nbsp;Name = "Category1",&nbsp; &nbsp; &nbsp;Score = 10,&nbsp; &nbsp; &nbsp;Count = 3});使用 System.Linq 对类别进行排序var sortedCategores = categories.OrderByDescending(x => x.Score).ThenByDescending(x => x.Count).ToList();循环访问集合foreach(var category in sortedCategores){&nbsp; &nbsp; Console.WriteLine($"{category.Name} [Score: {category.Score}] [Count: {category.Count}]");}

有只小跳蛙

可能最简单的方法是创建一个类来保存每个列表中的关联属性,而不是尝试管理一堆列表及其项的顺序。我们还可以重写此类的 ToString 方法,以便它输出您当前默认使用的格式化字符串:class Category{&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public int Count { get; set; }&nbsp; &nbsp; public int Score { get; set; }&nbsp; &nbsp; public override string ToString()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $"{Name} [Score: {Score}] [Count: {Count}]";&nbsp; &nbsp; }}然后,您可以创建此类型的单个列表,而不是三个不同的列表。下面是一个示例,它使用现有列表来填充新列表,但理想情况下,您可以修改向三个列表添加项的代码,而不是向单个列表添加新项。拥有此单个列表后,可以使用扩展方法 OrderBy(将最小的项目放在前面)或 OrderByDescending(将最大的项目放在第 一位)按您喜欢的任何属性(然后按任何其他属性)对其进行排序:CategorySystem.Linqvar 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 listsfor (int i = 0; i < categories.Count; i++){&nbsp; &nbsp; items.Add(new Category&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Name = categories[i],&nbsp; &nbsp; &nbsp; &nbsp; Count = count[i],&nbsp; &nbsp; &nbsp; &nbsp; Score = score[i]&nbsp; &nbsp; });}// Now you can sort by any property, and then by any other property// OrderBy will put smallest first, OrderByDescending will put largest firstitems = items.OrderByDescending(item => item.Score)&nbsp; &nbsp; .ThenByDescending(item => item.Count)&nbsp; &nbsp; .ToList();// Write each item to the consoleitems.ForEach(Console.WriteLine);GetKeyFromUser("\nDone! Press any key to exit...");输出
随时随地看视频慕课网APP
我要回答