List去重方法
方法一:遍历list
循环遍历List,借助Dictionary存储去重的对象
Dictionary<string, Item> result = new Dictionary<string, Item>();
foreach (Item item in list)//list为待去重列表
{
Item temp;
if (!result.TryGetValue(item.name, out temp))
{
result.Add(item.name, item);
}
}
List<Item> result_list = result.Values.ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}
方法二:ToLookup
利用ToLookup查找,并转为Dictionary
List<Item> result = list.ToLookup(item => item.name).ToDictionary(item => item.Key, item => item.First()).Values.ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}
方法三:自定义Compare
自定义Compare方法实现
List<Item> result = list.Distinct(new Compare()).ToList();
//compare方法
public class Compare : IEqualityComparer<Item>
{
public bool Equals(Item a, Item b)
{
return a.name == b.name;
}
public int GetHashCode(Item obj)
{
return obj.name.GetHashCode();
}
}
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}
方法四:groupby
利用GroupBy分组实现
List<Item> result = list.GroupBy(item => item.name).Select(item => item.First()).ToList();
///Item
public class Item
{
public string name { get; set; }
public string value { get; set; }
}