Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use LINQ to query a generic collection

Tags:

c#

generics

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

like image 877
user1131926 Avatar asked Dec 13 '22 06:12

user1131926


2 Answers

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>

like image 71
Nuffin Avatar answered Dec 14 '22 22:12

Nuffin


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.

like image 33
phoog Avatar answered Dec 14 '22 20:12

phoog