日期:2014-05-18  浏览次数:20842 次

问个N个条件中任选M个条件的问题,类似于排列组合
C# code

//比如有以下5个条件
Func<string, bool> Filter1 = x => x.Distinct().Count() == 3 && x.Any(y => data1.Contains(y));
Func<string, bool> Filter2 = x => x.Distinct().Count() == 3 && x.Any(y => data2.Contains(y));
Func<string, bool> Filter3 = x => x.Distinct().Count() == 3 && x.Any(y => data3.Contains(y));
Func<string, bool> Filter4 = x => x.Distinct().Count() == 3 && x.Any(y => data4.Contains(y));
Func<string, bool> Filter5 = x => x.Distinct().Count() == 3 && x.Any(y => data5.Contains(y));

//现在欲求其中任意满足2-3个条件交集输出
//此时,就是5个条件中任选2个进行交集,任选3个进行交集,再把两个交集做并集
Func<string, bool> Filter = x => true;
Filter = x => Filter1(x) && Filter2(x) + Filter1(x) && Filter3(x)+.....+Filter3(x) && Filter4(x)&& Filter5(x);//问题1:并集是否不对??有没有更好的方法?
var result = Enumerable.Range(0, 200).Where(x => Filter(x.ToString().PadLeft(3, '0')));

问题2:5个中任选2-3个条件的组合已经很多了,如果改成100个任选10-15个条件呢?估计就崩溃了,求一通用、简化算法。



------解决方案--------------------
filter = x => new bool[] { filter1(x), filter2(x), filter3(x), filter4(x), filter5(x) }.Where(y => y).Count() > 2;

不在括号里面。这个过滤器会选择那些5个条件中最少满足2个条件的数据。