I wanted to know the way to LINQ a generic collection.
My Customer class is as
class Customer
{
public string Name { get; set; }
public string id { get; set; }
}
My collection class is
class genericCollection<T> : CollectionBase
{
public void add(T GenericObject)
{
this.List.Add(GenericObject);
}
}
Then I add some data to customer collection
genericCollection<Customer> customers = new genericCollection<Customer>();
customers.add(new Customer {id= "1",Name="Andy"});
customers.add(new Customer { id = "2", Name = "MArk" });
customers.add(new Customer { id = "3", Name = "Jason" });
customers.add(new Customer { id = "4", Name = "Alex" });
Now i can iterate through customers object using a foreach loop but how can i linq it.
I want to use something like
var query = from c in customers
select c;
But I am not able to successfully cast it.
Regards, Sab
try to change your query to the following (assuming that your CollectionBase
implements IEnumerable
):
var query = from c in customers.OfType<Customer>() select c;
or let your genericCollection<T>
implement IEnumerable<T>
Some answers suggest using customers.OfType<Customer>
; this tests the type of every object in the collection before converting it. You know that each object is of that type, so you don't need the runtime type check. For that reason, you should use customers.Cast<Customer>
instead.
Having said that, I agree that it would be better not to use CollectionBase
in the first place; it would be better to use a generic collection type; if you prefer to define your own collection type, then you should derive from (or delegate to) a generic collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With