我有一個字符串列表,每個字符串的長度都是可變的。我想從列表中排除一個子集,該列表中的字符串從長度等於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)所需的輸出? – recursive
因爲abc + ab已經產生了輸出,所以你不需要再考慮abc和ab,直到找到下一個abc或ab。 – Mike
我想你正在尋找[cross join](http://stackoverflow.com/questions/56547/how-do-you-perform-a-cross-join-with-linq-to-sql)filteredList到自己,而不是「Aggregate」調用(假設「所有組合」意味着所有組合:)) –