[英]how can i create a programmatically sort order in C# on a grouped collection
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例如,假设我有我的 IssueTypes
"City Level" “市级”
"State Level" “国家级”
"Country Level" “国家级”
i want to loop through the "groupbyIssueType collection in the order Country, State, City我想按国家、State、城市的顺序遍历“groupbyIssueType”集合
what would be the best way of doing that?这样做的最好方法是什么?
You need to write an IComparer<String>
that uses your custom sort order.您需要编写一个使用自定义排序顺序的
IComparer<String>
。
For example:例如:
static string[] order = { ... };
public int Compare(string x, string y) {
return Array.IndexOf(order, x).CompareTo(Array.IndexOf(order, y));
}
A simple way to code it without creating new classes or enums or something with complicated logic would be to create a list or array of strings that are in your desired order, such as在不创建新类或枚举或具有复杂逻辑的东西的情况下对其进行编码的一种简单方法是创建一个按您想要的顺序排列的字符串列表或数组,例如
List<string> items = new List<string>() { "C", "A", "D", "E", "B" };
Then you can use this as the first or controlling sequence in a join operation.然后,您可以将其用作连接操作中的第一个或控制序列。 The order of the items above will be preserved, which means your other sequence will then be sorted to your custom rule.
以上项目的顺序将被保留,这意味着您的其他顺序将按照您的自定义规则进行排序。
var orderedGroupedItems = from item in items
join foogroup in groupedFoos
on item equals foo.Key
select foogroup;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.