Mr *_*les 0 c# linq list rally
我有一组字符串,如下所示:
"[Unfinished] Project task 1"
"Some other Piece of work to do"
"[Continued] [Unfinished] Project task 1"
"Project Task 2"
"Random other work to do"
"Project 4"
"[Continued] [Continued] Project task 1"
"[SPIKE] Investigate the foo"
Run Code Online (Sandbox Code Playgroud)
我想要做的是根据字符串按字母顺序排序这些字符串,但忽略方括号中的值.所以我希望最终结果是:
"[SPIKE] Investigate the foo"
"Project 4"
"[Continued] [Continued] Project task 1"
"[Continued] [Unfinished] Project task 1"
"[Unfinished] Project task 1"
"Project Task 2"
"Random other work to do"
"Some other Piece of work to do"
Run Code Online (Sandbox Code Playgroud)
题:
如何在LINQ中实现这一点,这是我必须要做的:
collection.OrderBy(str => str)
Run Code Online (Sandbox Code Playgroud)
听起来你应该编写一个方法来检索"不在括号中的字符串部分"(例如使用正则表达式).然后你可以使用:
var ordered = collection.OrderBy(RemoveTextInBrackets);
Run Code Online (Sandbox Code Playgroud)
你的RemoveTextInBrackets方法可能只想删除字符串开头的东西,以及它后面的空格.
完整的例子:
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
private static readonly Regex TextInBrackets = new Regex(@"^(\[[^\]]*\] )*");
public static void Main()
{
var input = new[]
{
"[Unfinished] Project task 1 bit",
"Some other Piece of work to do",
"[Continued] [Unfinished] Project task 1",
"Project Task 2",
"Random other work to do",
"Project 4",
"[Continued] [Continued] Project task 1",
"[SPIKE] Investigate the foo",
};
var ordered = input.OrderBy(RemoveTextInBrackets);
foreach (var item in ordered)
{
Console.WriteLine(item);
}
}
static string RemoveTextInBrackets(string input) =>
TextInBrackets.Replace(input, "");
}
Run Code Online (Sandbox Code Playgroud)