2011-02-02 35 views
3

我有業務對象集合如何LINQ結果伊斯利轉換爲業務對象集合<T>

我想篩選使用LINQ行,但發現它返回IEnumerable的東西不能再投給我的BOC

例如,我不能這樣做,

BOC <Client> bocCLients = (BOC <Client>) 
          from C in ClientsColl where C.ClientId == 100 select C 

我已經解決了通過LINQ結果循環和增加返回的對象到我原來的集合。

我不知道是否有更簡單的方法?

回答

1
var bocCLients = ClientsColl.Where(c => c.ClientId == 100).ToList(); 

或者

var bocCLients = new BOC<Client>(ClientsColl.Where(c => c.ClientId == 100)); 

編輯 或者,也許一個擴展的AddRange

public static void AddRange<T>(this ICollection<T> colSource, IEnumerable<T> collection) 
     { 
      if (colSource is List<T>) 
       ((List<T>)colSource).AddRange(collection); //If List use build in optimized AddRange function 
      else 
      { 
       foreach (var item in collection) 
        colSource.Add(item); 
      } 
     } 
+0

感謝很好的提示,但#1創建列表,不BOC ,#2需要額外的BOC構造接受IEnumerabel我覺得呢? – Maciej 2011-02-02 11:54:38

1

這看起來像一個完美的機會來創建一個擴展方法。從看你的問題看來,ClientsColl已經包含了Client類型的對象。在這種情況下,你的foreach循環的解決方案是理想的。但是,您可以將該解決方案封裝到擴展方法中,並使其可重用並易於閱讀。

下面是它會是什麼樣子的例子:

public static BOC<T> ToBOC<T>(this IEnumerable<T> sourceCollection) 
{ 
    var boc = new BOC<T>(); 
    foreach (T item in sourceCollection) 
    { 
     boc.Add(item); 
    } 
    return boc; 
} 

使用這種擴展方法,你只寫你的查詢,如下所示:

BOC<Client> bocClients = 
(
    from C in ClientsColl 
    where C.ClientID == 100 
    select C 
).ToBOC(); 

編輯

跟進更加通用的擴展方法到ICollection的想法,但保持原來的問題是執行一個排序轉換爲特定類型的集合,現在有中行實現ICollection的新的信息,這裏是一個比較通用的擴展方法和用途進行工作:

public static TCollection ToICollection<T, TCollection>(this IEnumerable<T> sourceCollection) 
     where TCollection : ICollection<T>, new() 
    { 
     TCollection col = new TCollection(); 
     foreach (T item in sourceCollection) 
     { 
      col.Add(item); 
     } 
     return col; 
    } 

與用法:

BOC<Client> bocClients2 = 
(
    from C in ClientsColl 
    where C.ClientID == 100 
    select C 
).ToICollection<Client, BOC<Client>>(); 

這看起來更有用嗎?讓我知道你的想法。

+1

@大衛或擴展方法ICollection的所謂的AddRange,這不上面。會比任何集合,不僅BOC Magnus 2011-02-02 12:16:25

相關問題