实现model数组 (model 字段为 id name type)按id去重,Distinct实现
Model m1 = new Model(1, "张三", "男");
Model m2 = new Model(2, "李四", "男");
Model m3 = new Model(1, "王五", "男");
List<Model> list = new List<Model>();
list.Add(m1);
list.Add(m2);
list.Add(m3);
去重后留“张三”还是“王五”?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DistinctDemo
{
internal class Program
{
static void Main(string[] args)
{
var people = new List<Person>() {
new Person{ Id = 1, Name = "张三"},
new Person{ Id = 2, Name = "赵四"},
new Person{ Id = 1, Name = "王五"},
};
Distinct<Person>(ref people, MyCondition);
}
private static bool MyCondition(Person person1, Person person2)
{
if (person1 == null && person2 == null)
{
return true;
}
if (person1 == null || person2 == null)
{
return false;
}
return person1.Id == person2.Id;
}
static void Distinct<T>(ref List<T> list, Func<T, T, bool> Condition) // ref不用也行,加上语义明确一些
{
if (list != null && list.Count > 1)
{
for (int i = 1; i < list.Count; i++)
{
for (int j = 0; j < i; j++)
{
if (Condition(list[i], list[j]))
{
list.RemoveAt(i--);
}
}
}
}
}
}
internal class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
或者:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DistinctDemo
{
internal class Program
{
static void Main(string[] args)
{
var people = new List<Person>() {
new Person{ Id = 1, Name = "张三"},
new Person{ Id = 2, Name = "赵四"},
new Person{ Id = 1, Name = "王五"},
};
people = people.Distinct(new MyEqualityComparer()).ToList();
}
}
internal class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
internal class MyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Id == y.Id;
}
public int GetHashCode(Person obj)
{
return obj.Id.GetHashCode();
}
}
}
好的,现在以解决
用HashSet或者LinkedHashSet,并重写equals,hashcode方法,id相同时equals返回true
抱歉,你说的这个我不是很清楚。
哥,我刚刚上网查了你说的这两个是java里的集合,这两个是好像是添加不重复,但我这个是根据id属性,通过Distinct去重复
@宋人鱼:
是可以实现的,不过我以为是Java的
讲道理这些都是基础应用,看你三天两头在这里问问题,每次都是些基础,感觉大家蹭豆蹭得都不习惯了,要不先学下基础吧,B站上好多学习视频;整体学习下,构建自己的知识体系,不然今天一个点明天一个点也容易忘,学习效率也低
https://search.bilibili.com/all?vt=35295100&keyword=C%23&from_source=webtop_search&spm_id_from=333.1007
@飒沓流星: 好的,谢谢
list.DistinctBy(p => p.id);
好的,谢谢
要啥语言的哇
C#,现在已经解决了
楼主这个应该C#编写的。
可以new一个新的字典(Dictionary<int,Model>),然后遍历list
Dictionary<int,Model> dic=new Dictionary<int,Model>();
foreach(Model item in list)
{
if(dic.keys.contains(item.Id))
continue;
dic.add(item.Id,item);
}
dic即为去重结果。
好的,知道了,谢谢