您可以使用LINQ輕鬆解決這類問題。
var solutions = from pair1 in listOne
where IsCandidate(pair1)
from pair2 in listTwo
where IsCandidate(pair1, pair2)
from pair3 in listThree
where IsCandidate(pair1, pair2, pair3)
from pair4 in listFour
where IsCandidate(pair1, pair2, pair3, pair4)
from pair5 in listFive
where IsCandidate(pair1, pair2, pair3, pair4, pair5)
from pair6 in listSix
where IsCandidate(pair1, pair2, pair3, pair4, pair5, pair6)
from pair7 in listSeven
where IsSolution(pair1, pair2, pair3, pair4, pair5, pair6, pair7)
select new { pair1, pair2, pair3, pair4, pair5, pair6, pair7 };
當然,這種方法是有效的,因爲列表數量在編譯時是已知的。另一種方法是建立可能的組合的通用方法,如Eric Lippert shows in his post。
遍及查詢的所有中介where
都將盡快過濾出無效組合。
EDIT
固定溶液有效地計數相同組合多少次發生時,忽略原始源的密鑰。
爲了實現這一點,我將對每個字典應用一個轉換。我將把每個字典轉換爲一個新的字典,其中鍵是枚舉值,並且該值將是枚舉值在原始字典中發生的次數。
IDictionary<MyEnum, int> CountOccurrences(IEnumerable<MyEnum> values)
{
return (from e in values group e by e).ToDictionary(grp => grp.Key, grp => grp.Count());
}
var solutions = from p1 in CountOccurrences(listOne.Values)
where IsCandidate(p1)
from p2 in CountOccurrences(listTwo.Values)
where IsCandidate(p1, p2)
from p3 in CountOccurrences(listThree.Values)
where IsCandidate(p1, p2, p3)
from p4 in CountOccurrences(listFour.Values)
where IsCandidate(p1, p2, p3, p4)
from p5 in CountOccurrences(listFive.Values)
where IsCandidate(p1, p2, p3, p4, p5)
from p6 in CountOccurrences(listSix.Values)
where IsCandidate(p1, p2, p3, p4, p5, p6)
from p7 in CountOccurrences(listSeven.Values)
where IsSolution(p1, p2, p3, p4, p5, p6, p7)
select new {
E1 = p1.Key,
E2 = p2.Key,
E3 = p3.Key,
E4 = p4.Key,
E5 = p5.Key,
E6 = p6.Key,
E7 = p7.Key,
Times = p1.Value * p2.Value * p3.Value * p4.Value * p5.Value * p6.Value * p7.Value
};
你可以定義什麼樣的組合看起來像你在組合上使用的一些示例邏輯?你能定義所有可能的組合的含義嗎? – mellamokb 2011-05-02 17:11:47
如果該方法是通用的,那麼您別無選擇,只能檢查每個組合,並且需要運行eon。一個短暫但典型的輸入 - >輸出是必要的。 – 2011-05-02 17:14:42