对List集合数据去重的方法有很多,在这里对其中一种用到的简便的方法进行记录一下。可以使用List自带的GroupBy方法进行分组,然后使用Select和First方法选取分组数据后的第一个元素,最后将结果ToList()即可。示例代码如下:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleAppDemo
{
class Program
{
private class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
static void Main(string[] args)
{
TestDistinct();
Console.ReadLine();
}
private static void TestDistinct()
{
List<Product> productList = new List<Product>();
productList.Add(new Product() { Id = 100, Name = "香蕉" });
productList.Add(new Product() { Id = 101, Name = "橙子" });
productList.Add(new Product() { Id = 100, Name = "香蕉" });
productList.Add(new Product() { Id = 102, Name = "葡萄" });
productList.Add(new Product() { Id = 101, Name = "橙子" });
productList.Add(new Product() { Id = 103, Name = "西瓜" });
//去重
List<Product> products = productList.GroupBy(x => x.Id).Select(x => x.First()).ToList();
//去重后的结果
string data = JsonConvert.SerializeObject(products);
Console.WriteLine(data);
/*
data内容:[{"Id":100,"Name":"香蕉"},{"Id":101,"Name":"橙子"},{"Id":102,"Name":"葡萄"},{"Id":103,"Name":"西瓜"}]
*/
}
}
}