【发布时间】:2013-10-23 13:38:37
【问题描述】:
我有一个字符串列表,每个字符串的长度都是可变的。我想从列表中投影一个子集,该子集的字符串从原始列表连接起来,长度等于 5。我正在使用聚合函数,但它没有给我想要的结果。对于这个投影,什么是合适的 LINQ 查询?你能帮忙吗?
代码:
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;
}
}
几点:
一旦处理了一个项目,我不需要再次考虑该项目的组合
以上是真的,直到我在列表中再次找到相同的项目,一旦我找到它,我应该尝试将它与之前连接中未使用的另一个项目连接。
不需要是LINQ,我只是在寻找解决方案。
输出不能包含两个以上的字符串? (a + bc + de) 不是必需的。
项目不需要与自身连接。
我在问题中提到了输出。
注意:使用 .NET 3.5(但如果可能,也希望看到 .NET 4.0 中的快捷方式)
【问题讨论】:
-
我不确定我是否理解这个要求。为什么 ababc (ab + abc) 不是理想的输出?
-
因为 abc+ab 已经产生了输出,然后就不需要再考虑 abc 和 ab 了,直到找到下一个 abc 或 ab。
-
我认为您正在寻找过滤列表的cross join 本身,而不是
Aggregate调用(假设“所有组合”表示所有组合:)) -
必须是linq吗?
-
输出是否可以包含两个以上的字符串? (a + bc + de)