0

I am using Entity Framework 5.0 and I have this Person class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I use OrderBy on an IEnumerable object:

 IEnumerable lstPerson<Person>

I found that I can use

 lstPerson = lstPerson.OrderBy("FirstName", SortDirection.Ascending);

But when I get the lstPerson from database, I must use

lstPerson.OrderBy(e => e.FirstName);

Why I can not use

 lstPerson.OrderBy("FirstName", SortDirection.Ascending) 

with IEnumerable from database?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Willard
  • 43
  • 4
  • `IEnumerable lstPerson` - this does not look like something which will compile in C#. – Guru Stron Sep 04 '22 at 04:59
  • 1
    And `.OrderBy("FirstName",SortDirection.Ascending)` does not look like something from BCL, but maybe I'm forgetting something. Either way you should not use methods based on `IEnumerable` when working with EF, only `IQueryable` ones. – Guru Stron Sep 04 '22 at 05:01
  • *"Why I can not use..."*. Because you can't just make up methods that seem convenient. You can only call methods that actually exist. – user18387401 Sep 04 '22 at 07:30
  • Presumably `IEnumerable lstPerson` should be `IEnumerable lstPerson`. – user18387401 Sep 04 '22 at 07:31
  • 1
    Using `IEnumerable` could be catastrophically bad for large data - that does things client side. To move things server side, you need to retain `IQueryable`. For a string (member-name) based sort: try https://stackoverflow.com/a/233505/23354 – Marc Gravell Sep 04 '22 at 08:43
  • Check this one too for IQueryable/IEnumerable differences: https://stackoverflow.com/a/2876655/3231884 – Luis Gouveia Nov 10 '22 at 10:51

1 Answers1

0

You can use lstPerson.OrderBy(e => e.FirstName) because there is an extension method that microsoft has written that works on an IEnumerable if you supply it a predicate ie e => e.FirstName.

You cannot use lstPerson.OrderBy("FirstName", SortDirection.Ascending) because there is no method that works on an IEnumerable if you supply it a string and a SortDirection.

There is a method called GridView.Sort that you might be familiar with, but that one only works on a GridView (if you provide it a string and a SortDirection). You arent working with a gridview here so it cant be used.

Slack Groverglow
  • 846
  • 7
  • 25
  • 1
    To be precise, that method works on an `IEnumerable` rather than an `IEnumerable`, which would require a call to `Cast` first. – user18387401 Sep 04 '22 at 07:32