Если у вас нет специального класса, представляющего ваш объект Line
, вы можете использовать regex
для анализа строки.В этом случае я использую name capture group
из 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();
или то же самое с беглым 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;
}
}
Этот код был взят из этот ответ .
Затем вы используете 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 - это вашдруг.