MHP
MHP

Reputation: 81

How to use .Where with lambda / IQueryable

Edit: Code works fine, it was an other bug.

I had comment out the //department.IdAgency = reader.GetByte(2); line, in the created departmentList. When I removed the // then the IQueryable<string> with .Where works fine. Sorry for the inconvenience!

static List<Department> CreateDepartmentList(IDataReader reader)
{
  List<Department> departmentList = new List<Department>();
  Department department = null;
  while (reader.Read())
  {
    department = new Department();
    department.Id = reader.GetByte(0);
    department.Name = reader.GetString(1);
    //department.IdAgency = reader.GetByte(2);

    if (!reader.IsDBNull(3))
    { department.IdTalkGroup = reader.GetInt16(3); }
    departmentList.Add(department);
  }
  return departmentList;
}

Original question:

I have an IQueryable<string> query, that works. But how do I use .Where?

IQueryable<string> query = departmentList.AsQueryable()
                                         .OrderBy(x => x.Name)
                                         .Select(x => x.Name);

I have tried this, but it does not work:

IQueryable<string> query = departmentList.AsQueryable()
                                         .OrderBy(x => x.Name)
                                         .Where(x => x.IdAgency == idAgencySelected[0])
                                         .Select(x => x.Name);

Upvotes: 0

Views: 966

Answers (1)

Andrew Gray
Andrew Gray

Reputation: 3790

All the .Where() call does is apply a filtering method to each element on the list, thus returning a new IEnumerable.

So, for some IQueryable<string>...

IEnumerable<string> results = SomeStringList.Where(s => s.Contains("Department"));

...You would get a list of strings that contain the word department.

In other words, by passing it some boolean condition that can be applied to a member of the queryable collection, you get a subset of the original collection.

The reason your second block of code does not work, is because you're calling a method or property that does not belong to string. You may want to consider querying against the more complex type, if it has identifier data, and then take the names of the elements and add them to some list instead.

Upvotes: 1

Related Questions