开发者

How to easly convert linq result to Business Object Collection <T>

I have Business Object Collection

I'd like to filter rows using linq, but noticed it returns IEnumerable what can not be cast then to my BOC

E.g I cannot do that

BOC <Client> bocCLients = (BOC <Client>) 
         开发者_StackOverflow中文版                 from C in ClientsColl where C.ClientId == 100 select C

I've resolved that by looping by linq results and adding returned object to my original collection.

I wonder if there is simpler way?


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

Or

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

Edit Or maybe an AddRange extension

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);
            }
        }


This looks like a perfect opportunity to create an extension method. From looking at your question, it appears that ClientsColl already contains objects of type Client. In this case, your solution of a foreach loop is ideal. However, you can encapsulate that solution into an extension method and make it reusable and easy to read.

Here's an example of how it would look like:

 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;
 }

Using this extension method, you would just write your query as follows:

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

EDIT:

To follow up on the idea of the more generic extension method to ICollection, but keeping in line the original question which was to perform a sort of Cast to a specific type of collection, and now having the new information that BOC implements ICollection, here is a more generic extension method and usage to perform the job:

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;
    }

And usage:

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

Does this look more useful? Let me know what you think.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜