0

I just stuck up with the issue, i am fetching data from database using entity framework, but facing problems.

Problem

My Role table has multiple Roles, it contains duplicate values like others 4 times, i am fetching it and binding it to dropdown, but i am getting others value 4 times in dropdown list

Here is the code that i am trying.

public List<RefrenceDataModel> GetJobRoles()
{
    List<RefrenceDataModel> lstRefrenceDataReturn = new List<RefrenceDataModel>();
    DataContext context = new DataContext();
    lstRefrenceDataReturn = context.JobsRoles.ToList().distinct().Select(items => new RefrenceDataModel() { RefrenceDataName = items.RoleName, RefrenceDataID = items.RoleID }).ToList<RefrenceDataModel>();
    return lstRefrenceDataReturn;
}

This code is returning duplicate values, but i don't want duplicates, what i am doing wrong?

2
  • Distinct(your implementation of IEqualityComparer<T>) Commented May 29, 2013 at 7:09
  • I expect it's not working because your RefrenceDataModel type does not implement IEquatable<RefrenceDataModel> properly or at all. (And as a side note, is RefrenceDataModel spelt right? ;)) Commented May 29, 2013 at 7:22

1 Answer 1

1

by using GroupBy

lstRefrenceDataReturn = context.JobsRoles
  .GroupBy(r => r.RoleName)
  .Select(g => g.FirstOrDefault())
  .Select(items => new RefrenceDataModel() { RefrenceDataName = items.RoleName, RefrenceDataID = items.RoleID }).ToList<RefrenceDataModel>();
Sign up to request clarification or add additional context in comments.

2 Comments

Tried .Select(g => g.FirstOrDefault()) instead .Select(g => g.First()) and it worked... Thanks Damith
@DhavalMarthak That's better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.