.distinct not working

Thread is closed for posting
3 posts, 0 answers
  1. Markus
    Markus avatar
    205 posts
    Member since:
    Nov 2005

    Posted 03 Jun 2013 Link to this post

    Good day all

    I am trying to create a pulldown with all distinct cities from a table. I use this code below.

    Any idea why the .Distinct() is not having any effect, and how I would have to create the statement?

    (I am NOT getting an error. Simply all cities  not filtered distinct)

    using (EntitiesModel dbContext = new EntitiesModel())
                       List<T_user> FirmenNachOrt = (from a in dbContext.T_users
                                                     where a.User_benutzung == "Firma" && a.User_freischaltung == false
                                                     orderby a.User_ort
                                                         select  a).Distinct().ToList();
                       rddl_firmen_nach_ort.DataSource = FirmenNachOrt;
                       rddl_firmen_nach_ort.DataTextField = "user_ort";
                       rddl_firmen_nach_ort.DataValueField = "user_ort";
                       rddl_firmen_nach_ort.Items.Insert(0, new DropDownListItem("Nach Ort suchen"));

  2. Viktor Zhivkov
    Viktor Zhivkov avatar
    324 posts

    Posted 03 Jun 2013 Link to this post

    Hi Markus,

    OpenAccess LINQ supports Distinct on the database server side only if you are doing it by a primitive property bound to a database column. If you are doing distinct by the whole entity object it will be done in-memory using .Net comparison rules.

    If you want to get only the distinct values from T_users.User_ort you should modify your query slightly:
    01.using (EntitiesModel dbContext = new EntitiesModel())
    03.    List<string> FirmenNachOrt = (from a in dbContext.T_users 
    04.                 where a.User_benutzung == "Firma" && a.User_freischaltung == false
    05.                 orderby a.User_ort 
    06.                 select  a.User_ort).Distinct().ToList();
    08.    // TODO: bind the combobox properly to the new List<string>

    If you need the whole T_users object, please implement a custom IEqualityComparer<T_users> and provide it as parameter of the Distinct method call. You should note that the filter will be applied in-memory and you will fetch some unnecessary data from the database.

    If you need any further assistance do not hesitate to contact us again.

    Viktor Zhivkov
    OpenAccess Samples Kit boasts 50+ sample applications providing diverse real-life business solutions. Click to read more and see OpenAccess ORM in action.
  3. Ru'a
    Ru'a avatar
    1 posts
    Member since:
    Oct 2017

    Posted 31 Oct 2017 in reply to Viktor Zhivkov Link to this post

Back to Top