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

时间:2019-02-12 02:58:13

标签: c#

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

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]
*/

如何执行排序操作,以得到上面的输出? (如果使用数组更容易实现,我也可以使用数组)

2 个答案:

答案 0 :(得分:3)

不建议使用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}]");
}

答案 1 :(得分:2)

最简单的方法可能是创建一个类,该类保存每个列表的关联属性,而不是尝试管理一堆列表及其项的顺序。我们也可以override the ToString method此类,使其默认输出您当前正在使用的格式化字符串:

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}]";
    }
}

然后,您可以创建一个这种类型的列表,而不是三个不同的列表。这是一个使用现有列表填充新列表的示例,但理想情况下,您将修改将代码添加到三个列表中的代码,而不是向单个列表添加新的Category。拥有此单个列表后,您可以使用System.Linq扩展方法,OrderBy(将最小的项放在首位)或任何您喜欢的属性(然后按其他属性)对其进行排序。 OrderByDescending(将最大的项目放在首位):

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...");

输出

![enter image description here