I have a collection of strings that are as follows:
"[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"
What i want to do is order these strings alphabetically based on the strings, but ignoring the values in square brackets. So I want the end result to be:
"[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"
Question:
how can this be achieved in LINQ, this is where I've got to:
collection.OrderBy(str => str)
It sounds like you should write a method that retrieves "the part of the string which isn't in brackets" (e.g. using regular expressions). Then you can use:
var ordered = collection.OrderBy(RemoveTextInBrackets);
Your RemoveTextInBrackets
method probably only wants to remove things at the start of the string, and also the space following it.
Complete example:
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, "");
}
See more on this question at Stackoverflow