How to use LINQ to query a common collection

I wanted to know the path to LINQ for the general collection.

My Customer class is

class Customer { public string Name { get; set; } public string id { get; set; } } 

My collection class

 class genericCollection<T> : CollectionBase { public void add(T GenericObject) { this.List.Add(GenericObject); } } 

Then I add some data to the client 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 the clients object using the foreach loop, but how can linq do it.

I want to use something like

 var query = from c in customers select c; 

But I can not successfully apply it.

Regards, Sub

+4
source share
6 answers

Some answers recommend using customers.OfType<Customer> ; this checks the type of each object in the collection before converting it. You know that every object has this type, so you don't need to check the runtime type. For this reason, you should use customers.Cast<Customer> .

Having said that, I agree that it is 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 get (or delegate) a common collection.

+3
source

try changing your query to the following (assuming your CollectionBase implements IEnumerable ):

 var query = from c in customers.OfType<Customer>() select c; 

or let your genericCollection<T> implement IEnumerable<T>

+5
source

The standard LINQ query operators are extension methods defined for IEnumerable and IEnumerable<T> . You can try:

 class genericCollection<T> : Collection<T> 

or use another type of collection, for example List<T>

+2
source

You need to implement the IEnumerable<T> interface:

 public class genericCollection<T>: CollectionBase, IEnumerable<T>{} 
+1
source

The problem is what you get from CollectionBase . You must also implement ICollection<T> , and no casting is required anymore.

+1
source

You can specify the type in a LINQ query:

 var query = from Customer c in customers select c; 

or implement IEnumerable<T> , for example:

 class genericCollection<T> : CollectionBase, IEnumerable<T> { public void add(T GenericObject) { this.List.Add(GenericObject); } public IEnumerator<T> GetEnumerator() { return this.List.Cast<T>().GetEnumerator(); } } 
+1
source

Source: https://habr.com/ru/post/1389438/


All Articles