[英]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.我正在使用 linq 编写查询,每当我在表单中创建新条目时,性别下拉列表都会在该列表中生成重复项。如果我创建 2 个新条目 2 个这样的选项。 [male female male male ]. 【男女男男】。 my project is visual studio-angularJS-web api-linq-sql-entity framework.我的项目是visual studio-angularJS-web api-linq-sql-entity 框架。
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. Linq 有一个 Distinct() 方法,它将使用默认的相等方法来确保每个项目只返回一个副本。
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.要解决这个问题,您需要重载 Equals 和 GetHashCode。
Also, the order items will come out of Distinct is not guaranteed.此外,不能保证订单商品会从 Distinct 中出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.