如何在分组集合上的C#中以编程方式创建排序顺序 [英] how can i create a programmatically sort order in C# on a grouped collection

查看:43
本文介绍了如何在分组集合上的C#中以编程方式创建排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它按字符串字段进行收集和分组:

i have this code that take a collection and groups by a string field:

 var groupByIssueType = issues.GroupBy(r => r.IssueType);

我现在想遍历每个组,但是我想按指定的顺序进行.就像是 ..

i now want to loop through each group but i want to do that in a specify order. something like . .

foreach (var issueType in groupByIssueType)
{
}

问题在于顺序不是字母顺序的,所以我不能只做

The problem is that the order is not alphabetic so i can't just do an

 OrderBy(r=>r.Name)

或类似的东西...我需要一种通过其键对分组集合进行排序的方法,但需要使用自定义排序算法

or something like that. . . i need a way to sort a grouped collection by its keys but using a custom sorting algorithm

例如,假设我的问题类型为

So for example, lets say i have as my IssueTypes

城市等级"
州级"
国家/地区级别"

"City Level"
"State Level"
"Country Level"

我想按国家,州,城市"顺序遍历"groupbyIssueType"集合

i want to loop through the "groupbyIssueType collection in the order Country, State, City

什么是最好的方法?

推荐答案

您需要编写使用自定义排序顺序的 IComparer< String> .

You need to write an IComparer<String> that uses your custom sort order.

例如:

static string[] order = { ... };
public int Compare(string x, string y) {
    return Array.IndexOf(order, x).CompareTo(Array.IndexOf(order, y));
}

这篇关于如何在分组集合上的C#中以编程方式创建排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆