如果您没有代表您的Line 对象的特殊类,那么您可以使用regex 来解析字符串。在这种情况下,我使用name capture group of Regex:
List<string> elements = new List<string>
{
"Line 1 int 1",
"Line 2 int 1",
"Line 1 int 2",
"Line 1 int 3",
"Line 2 int 2",
"Line 2 int 12",
};
var pattern = @"^\bLine \b(?<num1>\d+) \bint \b(?<num2>\d+)$";
Regex regex = new Regex(pattern);
var query =
from e in elements
where regex.Match(e).Success
orderby
int.Parse(regex.Match(e).Groups["num1"].Value),
int.Parse(regex.Match(e).Groups["num2"].Value)
select e;
var orderedResult = query.ToList();
或与 fluent API LINQ 相同:
var orderedResult =
elements
.Where(e => regex.Match(e).Success)
.OrderBy(e => int.Parse(regex.Match(e).Groups["num1"].Value))
.ThenBy(e => int.Parse(regex.Match(e).Groups["num2"].Value))
.ToList();
orderedResult 应该是:
Line 1 int 1
Line 1 int 2
Line 1 int 3
Line 2 int 1
Line 2 int 2
Line 2 int 12
更新:
创建一个类和扩展方法,将您的列表分成块:
public static class MyLinqExtensions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(
this IEnumerable<T> source, int batchSize)
{
using (var enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return YieldBatchElements(enumerator, batchSize - 1);
}
private static IEnumerable<T> YieldBatchElements<T>(
IEnumerator<T> source, int batchSize)
{
yield return source.Current;
for (int i = 0; i < batchSize && source.MoveNext(); i++)
yield return source.Current;
}
}
此代码取自this answer。
那么你使用Batch扩展方法如下:
List<int> coord = new List<int> { 80, 90, 100, 60, 70, 20, 40, 30, 10, 50 };
int n = 5;
var orderedResult =
coord.Batch(n)
.Select(b => b.OrderBy(i => i))
.SelectMany(x => x)
.ToList();
如果你想学习 LINQ,LINQPad 是你的朋友。