简体   繁体   中英

How to avoid the duplicates in drop-down list by using linq?

I am using linq to write the query, whenever I am creating a new entry in a form,gender drop down list is generating duplicates in that list.if i create 2 new entries 2 options like this. [male female male male ]. my project is visual studio-angularJS-web api-linq-sql-entity framework.

something like

var filteredList = originalList
  .GroupBy(x => x.Gender)
  .Select(group => group.First());

Linq has a Distinct() method, which will use the default equality methods to ensure only one copy of each item is returned.

var items = new List<string>{'bob', 'frank', 'bob', 'jim'};
var distinctItems = items.Distinct();
//items should have 3 items, bob frank and jim

However if you're dealing with objects the default equality methods will be reference - meaning you'll get one copy of each object, but two objects with identical fields won't be considered equal. To fix that you need to overload Equals and GetHashCode.

Also, the order items will come out of Distinct is not guaranteed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM