[英]LINQ OrderBy with IEnumerable<T> key
I have an IEnumerable that I want to sort not within each sequence but from sequence to sequence. 我有一个IEnumerable,我不想在每个序列中进行排序,而是要在序列之间进行排序。
new [] {"Z", "B", "C" }
new [] {"A", "B", "C" }
new [] {"B", "B", "C" }
becomes 变
new [] {"A", "B", "C" }
new [] {"B", "B", "C" }
new [] {"Z", "B", "C" }
Is there an existing approach with LINQ or do I need to roll my own IComparer? LINQ是否有现有方法,还是需要推出自己的IComparer?
There's nothing built in. It's straightforward to roll your own helper method; 没有内置的东西。直接滚动自己的辅助方法很简单。 it's one line provided that the sequences are the same length .
只要序列的长度相同,就只有一行。
static int SequenceCompare<T>(
this IEnumerable<T> x,
IEnumerable<T> y,
Func<T, T, int> comparer) =>
x.Zip(y, comparer).FirstOrDefault(c => c != 0);
Now if you can compare two members of a sequence, you can also compare two sequences. 现在,如果您可以比较序列的两个成员,则还可以比较两个序列。
This doesn't work if the sequences are of unequal length; 如果序列长度不相等,则此方法无效。 you have to do a bit more work to say that "A", "B", "C" is "bigger" than "A", "B".
您必须做更多的工作才能说“ A”,“ B”,“ C”比“ A”,“ B”“大”。
Exercise: Solve the problem for sequences of unequal length. 练习:解决长度不等的问题。 (Hint: Examine the implementation of
Zip
and modify it accordingly.) (提示:检查
Zip
的实现并进行相应的修改。)
Exercise: Suppose we have a comparison function Func<T, T, int>
. 练习:假设我们有一个比较函数
Func<T, T, int>
。 We've seen how to extend it to Func<IEnumerable<T>, IEnumerable<T>, int>
. 我们已经看到了如何将其扩展到
Func<IEnumerable<T>, IEnumerable<T>, int>
。 Now suppose the arguments were Task<T>
, or Func<T>
or Nullable<T>
or Lazy<T>
-- how might you similarly implement a comparison? 现在假设参数是
Task<T>
或Func<T>
或Nullable<T>
或Lazy<T>
-您将如何类似地实现比较? Which of those are easy and which of them are hard, and why? 其中哪些简单,哪些困难,为什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.