2013-12-20 46 views
1

其中考慮下面的函數LINQ忽略如果someobject爲null

public static string UpdateCommand<T>(List<string> Except=null,List<string> Only=null) 
     { 
      if (Except != null && Only != null) 
       { 
       throw new Exception(); 
       } 

     List<PropertyInfo> properties = typeof(T).GetProperties().ToList(); 


     if (Except != null) 
     { 
      for (int i = properties.Count; i-- > 0;) 
      { 
       if (Except.Contains(properties[i].Name)) properties.RemoveAt(i); 
      } 
     } 

     if(Only != null) 
     { 
      for (int i = properties.Count; i-- > 0;) 
      { 
       if (!Only.Contains(properties[i].Name)) properties.RemoveAt(i); 
      } 
     } 
     //etc... 
     } 

它需要2個任選參數它們既可以是空或其中一方可以具有價值,但它們中的至少一個應爲空。

我想弄清楚上面的Linq語法,有沒有辦法寫一個where語句,但忽略where語句,如果列表比較爲null?

基本上我正在尋找一種方法來使用LINQ來編寫上述代碼。

我不能使用交叉或除自2間不同類型的

回答

3
var result = properties 
    .Where(p => !(Except ?? Enumerable.Empty<String>()).Any(s => s == p.Name)) 
    .Where(p => Only == null || Only.Any(s => s == p.Name)) 
    .ToArray(); 
2

我建議你不要在這個方法管理過濾的。相反,你可以這樣做:

public static string UpdateCommand<T>(Func<IEnumerable<PropertyInfo>, IEnumerable<PropertyInfo>> filterFunc = null) 
{ 
    IEnumerable<PropertyInfo> properties = typeof(T).GetProperties(); 

    if (filterFunc != null) 
     properties = filterFunc(properties); 

    ... 
} 

使用方法如下:

UpdateCommand(pis => pis.Where(pi => ...)) 
2

這種類型的事情,最近關於可能的C#6.0的功能(項目7)的一篇文章中討論here。目前還沒有真正可行的解決方案,例如前面的答案所示。