2017-01-30 25 views
0

比方说,我有以下对象:从另一个对象生成所有可能的对象组合

public class Foo 
    { 
     public int? Prop1 { get; set; } 
     public int? Prop2 { get; set; } 
     public int? Prop3 { get; set; } 
    } 

初始化是这样的:

var test = new Foo(){ 
    Prop1 = 10, 
    Prop2 = 20, 
    Prop3 = 30 
} 

我想生成的所有可能的组合列表这些属性。 下面的列表将是一个可能的结果(基本上与所有可能的组合列表):

List[0] = new Foo{Prop1 = 10, Prop2 = null, Prop3 = null}; 
List[1] = new Foo{Prop1 = null, Prop2 = 20, Prop3 = null} 
List[2] = new Foo{Prop1 = null, Prop2 = null, Prop3 = 30}; 
List[3] = new Foo{Prop1 = 10, Prop2 = 20, Prop3 = null}; 
List[4] = new Foo{Prop1 = 10, Prop2 = null, Prop3 = 30}; 
List[5] = new Foo{Prop1 = null, Prop2 = 20, Prop3 = 30}; 
List[6] = new Foo{Prop1 = 10, Prop2 = 20, Prop3 = 30}; 

我使用LINQ或反射来尝试导航的所有属性和做什么....思考。当然,这可以通过大量的手动添加来完成,手动获取所有组合,并以长代码结束,但我相信有一种更简单的方法来实现这一点,所以..任何帮助将不胜感激。

感谢

+1

组合的顺序是否重要? –

+0

你是什么意思作为组合的顺序?如果你的意思是我需要那个例子中的List [0]是在0的位置,否则不重要,这只是一个例子。里面的值是对象的属性,所以你不能改变它们。 – Thal

+0

是的,我的意思是最终名单中的元素顺序 - 我的答案与上面的示例产生相同的组合,但顺序不同。 –

回答

2

狰狞危险方法将生成您的组合列表中的任意对象:

public List<T> CombinationsOf<T>(T template) 
{ 
    var properties = typeof(T).GetProperties().Where(prop => prop.CanRead && prop.CanWrite).ToArray(); 
    var combinations = 1 << properties.Length; 
    var result = new List<T>(combinations - 1); 
    for (var i = 1; i < combinations; i++) 
    { 
     var instance = (T)Activator.CreateInstance(typeof(T)); 
     var bits = i; 
     for (var p = 0; p < properties.Length; p++) 
     { 
      properties[p].SetValue(instance, (bits % 2 == 1) ? properties[p].GetValue(template) : properties[p].PropertyType.IsValueType ? Activator.CreateInstance(properties[p].PropertyType) : null); 
      bits = bits >> 1; 
     } 

     result.Add(instance); 
    } 

    return result; 
} 

用法:

var result = CombinationsOf(new Foo { Prop1 = 10, Prop2 = 20, Prop3 = 30 }); 

你可以改变外循环初始化程序到i = 0如果你想要“失踪”com bination将全部默认值。

警告:此代码是危险的 - 它:

  • 设置可能会损坏内部的状态的专用属性。
  • 调用可能导致副作用的代码的属性设置器和获取器。
  • 会产生错误的结果,如果有超过31个属性的< <操作员将包裹,你会产生错误的号码组合...
  • ...如果你不打这就是OutOfMemoryException异常可能与c发生。由于组合数量庞大,共有25个物业及以上。
+0

我可以理解**丑陋的**,但你为什么说**危险**? – Enigmativity

+1

非常好的解释。也许你应该把答案放在答案中? – Enigmativity

相关问题