LINQ的排序依据针对特定值 [英] Linq OrderBy against specific values
问题描述
有没有LINQ的一种方法做对一组值(在这种情况下,字符串)的排序依据不知道值的顺序?
考虑一下这个数据:
A
乙
一个
C
乙
C
ð
Ë
和这些变量:
第一串preF,第二preF,第三preF;
当值设置像这样:
第一preF ='A';
第二preF ='B';
第三preF ='C';
是否可以对数据进行排序,像这样:
A
一个
乙
乙
C
C
ð
Ë
如果你把你的preferences到一个列表,它可能会变得更加容易。
列表<串GT;数据=新的List<串GT; {A,B,A,C,B,C,D,E};
清单<串GT; preferences =新的List<串GT; {A,B,C};IEnumerable的<串GT; orderedData = data.OrderBy(
项目= GT; preferences.IndexOf(项目));
这将放在 preferences
没有出现的所有项目在前面,因为的IndexOf()
收益 1
。一个特设工作围绕可能扭转 preferences
和秩序的结果下降。这变得相当难看,但作品。
的IEnumerable<串GT; orderedData = data.OrderByDescending(
项目= GT; Enumerable.Reverse(preferences).ToList()的IndexOf(项目))。
该解决方案成为你一点更好CONCAT preferences
和数据
。
的IEnumerable<串GT; orderedData = data.OrderBy(
项目= GT; preferences.Concat(数据).ToList()的IndexOf(项目))。
我不喜欢 CONCAT()
和了ToList()
在那里。但目前我身边有没有真正的好办法。我找了一个很好的把戏转动 1
第一个例子变成了大数目。
Is there a way in Linq to do an OrderBy against a set of values (strings in this case) without knowing the order of the values?
Consider this data:
A
B
A
C
B
C
D
E
And these variables:
string firstPref, secondPref, thirdPref;
When the values are set like so:
firstPref = 'A';
secondPref = 'B';
thirdPref = 'C';
Is it possible to order the data like so:
A
A
B
B
C
C
D
E
If you put your preferences into a list, it might become easier.
List<String> data = new List<String> { "A","B","A","C","B","C","D","E" };
List<String> preferences = new List<String> { "A","B","C" };
IEnumerable<String> orderedData = data.OrderBy(
item => preferences.IndexOf(item));
This will put all items not appearing in preferences
in front because IndexOf()
returns -1
. An ad hoc work around might be reversing preferences
and order the result descending. This becomes quite ugly, but works.
IEnumerable<String> orderedData = data.OrderByDescending(
item => Enumerable.Reverse(preferences).ToList().IndexOf(item));
The solution becomes a bit nicer if you concat preferences
and data
.
IEnumerable<String> orderedData = data.OrderBy(
item => preferences.Concat(data).ToList().IndexOf(item));
I don't like Concat()
and ToList()
in there. But for the moment I have no really good way around that. I am looking for a nice trick to turn the -1
of the first example into a big number.
这篇关于LINQ的排序依据针对特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!