Remove duplicate object in list c#
Ngày đăng:
14/12/2021
Trả lời:
0
Lượt xem:
226
Home > c# > c# remove duplicates from list of objects C# remove duplicates from list of objects EditMurugan Andezuthu Dharmaratnam | It's easy to remove duplicates from a single dimensional array. The sample code below removes duplicates from a list of objects. The code will be able to remove duplicate Name, It does not compare all properties of the object. The first Id will be taken and the remaining will be ignored. SOLUTION 1public List GetFilteredList() { List lstcountries = new Country().Get(); List lstFiltered = new List(); foreach(var item in lstcountries) { if(!lstFiltered.Where(x => x.Name == item.Name).Any()) { lstFiltered.Add(item); } } return lstFiltered; }Code For Country Class & Datapublic class Country { public int Id { get; set; } public int Code { get; set; } public String Name { get; set; } public List Get() { ListOutput of code would be Solution 2lstcountries.Select(x => new { x.Name, x.Code} ).Distinct().ToList()This solution is if you do not want the Id, Any way Id will not be useful . Problem with the above code is it does not have an Id. Check the below code which will save the output to a list of Country. Please note all Id's in the below code will be 0 |