2017-01-30 24 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

相關問題