简体   繁体   中英

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

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

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

what would be the best way of doing that?

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM