我有IOrderedEnumerable<IGrouping<string,var>>
(IGrouping
中的值与问题无关,因此用var抽象)。我有一个List<string>
,其中包含用作IGrouping
键的字符串。我希望能够按键重新排序IOrderedEnumerable
,以便IGrouping
与List
的顺序保持一致。
我看过IOrderedEnumerable.OrderBy(v => v.Key)
,但这似乎只是按升序排列 - 我无法看到一种方法来欺负使用列表作为参考。我认为诀窍是写一个可以做到的键选择器,但我的LINQ-fu不够强大。
答案 0 :(得分:3)
_______][__________
如果您想避免再次为每个iOrderedEnumerable.OrderBy(v => thatListOfString.IndexOf(v.Key))
搜索列表,可以cache the positions in a dictionary:
v
答案 1 :(得分:0)
怎么样:
thatListOfString
.Select((orderIndex, stringValue)=>new{orderIndex, stringValue})
.Join(
orderedGroups,
left=>left.stringValue,
right=>right.Key,
(left,right)=>new{left,right}
)
.OrderBy(lr=>lr.left.orderIndex)//actually with current internal implementation of Enumerable.Join this one is not needed
.Select(lr=>lr.right);
答案 2 :(得分:0)
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication34
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
List<string> orderStrings = new List<string>() { "b", "a", "z" };
List<List<object>> data = new List<List<object>>() {
new List<object> {"a", 1},
new List<object> {"a", 2},
new List<object> {"a", 3},
new List<object> {"a", 4},
new List<object> {"b", 5},
new List<object> {"b", 6},
new List<object> {"b", 7},
new List<object> {"z", 8},
new List<object> {"z", 9},
};
var results = data.GroupBy(x => x[0]).OrderBy(x => orderStrings.IndexOf((string)x.Key)).ToList();
}
}
}