public static class UtilCombine
{
/// <summary>
/// 笛卡爾乘積算法
/// </summary>
public static List<List<T>> CartesianProduct<T>(this List<List<T>> lstSplit)
{
int count = 1;
lstSplit.ForEach(item => count *= item.Count);
//count = lstSplit.Aggregate(1, (result, next) => result * next.Count);
var lstResult = new List<List<T>>();
for (int i = 0; i < count; ++i)
{
var lstTemp = new List<T>();
int j = 1;
lstSplit.ForEach(item =>
{
j *= item.Count;
lstTemp.Add(item[(i / (count / j)) % item.Count]);
});
lstResult.Add(lstTemp);
}
return lstResult;
}
}
// var lstSource = new List<List<string>> // { // new List<string>() { "A","B","C"}, // new List<string>() { "D","E","F"}, // new List<string>() { "G","H","I"}, // }; // var sw = new Stopwatch(); // sw.Start(); // var lstResult = lstSource.CartesianProduct(); // HashSet<string> hs = new HashSet<string> (); //int index=1; // foreach (var item1 in lstResult) // { // string snn=item1[0]+item1[1]+item1[2]; // hs.Add(snn); // Console.WriteLine(snn +"=="+index); // index++; // } var lstSectorDef = new List<Sector> { new Sector{ name="顏色", value=new List<string>(){"紅色","黃色","綠色"}}, new Sector{ name="尺碼", value=new List<string>(){"L","M","S"}}, new Sector{ name="材質", value=new List<string>(){"皮質","棉布"}}, //.....數量不定 }; //第一步,去除各個規格的值,加入list var lstSource = new List<List<string>>(); foreach (var item in lstSectorDef) { lstSource.Add(item.value); } var sw = new Stopwatch(); sw.Start(); //調用算法,計算出組合的種類和總數量,生成多少個sku,每一種sku的規格值 var lstResult = lstSource.CartesianProduct(); HashSet<string> hs = new HashSet<string>(); int index = 1; foreach (var item1 in lstResult) { string snn = item1[0] +"-----"+ item1[1] +"-----"+ item1[2]; hs.Add(snn); Console.WriteLine(snn + "==" + index); index++; } Console.WriteLine(hs.Count); Console.WriteLine(sw.Elapsed);
非原創,網上找的各位大神的,只為方便以后查閱記錄,不喜勿噴
