I have a list of strings, each of variable length. I want to project a subset out of the list which has strings concatenated from the original list having length equal to 5. I'm using the aggregate function for it, but it's not giving me the desired result. What would be an appropriate LINQ query for this projection? Can you please help?
Code:
class Program
{
static void Main(string[] args)
{
IEnumerable<string> items = new List<string> {"abc", "ab", "abcd", "abcde", "abcdef", "a", "ab", "cde"};
//All combinations of concatenations equal to length 5.
//Only need to process an item once and need to concatenate 2 items and no more
var filteredList = items.Where(x => x.Length < 5)
.Aggregate(Execute).ToList();
foreach (var f in filteredList)
{
//Should out put : abc+ab = abcab
//Should out put : abcde
//Should out put : abcd+a = abcda
//Should out put : ab+cde = abcde
Console.WriteLine(f);
}
}
private static string Execute(string a, string b)
{
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
return null;
if ((a.Length + b.Length) == 5)
return a + b;
return null;
}
}
Couple of points:
Once an item is processed, I dont need to consider that item again for a combination
Above is true until I find the same item again in the list, once I find it I should try to concatenate it with another item which was not used in a previous concatenation.
No need of it to be LINQ, I'm just looking for a solution.
An output cannot consist of more than two strings? (a + bc + de) is not required.
An item need not be concatenated with itself.
I have mentioned the output as part of the question.
Note:Using .NET 3.5 (but would like to see a shortcut in .NET 4.0 as well if possible)