Steve Gaines
Steve Gaines

Reputation: 601

How to filter a generic list?

I have the code below which was working, but when I try to add the Where clause to filter the collection I get the error:

'object' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

I tried casting the object to OfType<Certification> and that failed. I also tried casting to IQueryable and that failed with a similar error. So I checked the type of my certifications variable and it is "System.Collections.Generic.List``1[[GainesTrader_WCF.Certification, GainesTrader WCF,". Can you see the solution to this?

    GainesTrader_WCF.Service1 client = new GainesTrader_WCF.Service1();
    object certifications = client.GetCertifications();
    //var filtered = certifications.OfType<Certification>().Where(o => o.CertificationAcronym == "MCSD");
    var filtered = certifications.Where(o => o.CertificationAcronym == "MCSD");
    Certifications.DataSource = filtered;
    Certifications.DataBind();

Upvotes: 0

Views: 796

Answers (2)

dfdsfdsfsdf
dfdsfdsfsdf

Reputation: 663

why is the certificates variable of type object? Look at the WCF proxy and verify the return type. When you set up the proxy, visual studio should've downloaded all related types.

Also, this is the first time, I've seen someone apply the Where extension method to a Object type. It doesn't even make sense.

Upvotes: 1

Wicher Visser
Wicher Visser

Reputation: 1543

You should cast your certifications variable to type IEnumerable<Certification>:

var filtered = certifications
  .OfType<IEnumerable<Certification>>()
  .Where(o => o.CertificationAcronym == "MCSD");

or

 var certifications = (IEnumerable<Certification>)client.GetCertifications();
 var filtered = certifications.Where(o => o.CertificationAcronym == "MCSD");

Upvotes: 1

Related Questions