How to easily convert linq result to <T> business object collection
I have a collection of business objects
I would like to filter strings using linq, but noticed that it returns IEnumerable, which cannot be dropped then in my BOC
For example, I can’t do it
BOC <Client> bocCLients = (BOC <Client>)
from C in ClientsColl where C.ClientId == 100 select C
I decided that by cyclizing using linq results and adding the returned object to my original collection.
I wonder if there is an easier way?
+3
2 answers
var bocCLients = ClientsColl.Where(c => c.ClientId == 100).ToList();
or
var bocCLients = new BOC<Client>(ClientsColl.Where(c => c.ClientId == 100));
Edit Or extension AddRange is possible
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);
}
}
+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, , Cast , , BOC 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