谁有一个快速的方法去重复在c#的泛型列表?
当前回答
如何:
var noDupes = list.Distinct().ToList();
在。net 3.5?
其他回答
如果你使用。net 3+,你可以使用Linq。
List<T> withDupes = LoadSomeData();
List<T> noDupes = withDupes.Distinct().ToList();
我有我自己的方式。我是2循环相同的列表比较列表项。然后去掉第二个。
for(int i1 = 0; i1 < lastValues.Count; i1++)
{
for(int i2 = 0; i2 < lastValues.Count; i2++)
{
if(lastValues[i1].UserId == lastValues[i2].UserId)
{
lastValues.RemoveAt(i2);
}
}
}
简单地用相同类型的List初始化HashSet:
var noDupes = new HashSet<T>(withDupes);
或者,如果你想返回一个List:
var noDupsList = new HashSet<T>(withDupes).ToList();
我认为最简单的方法是:
创建一个新列表并添加唯一的项目。
例子:
class MyList{
int id;
string date;
string email;
}
List<MyList> ml = new Mylist();
ml.Add(new MyList(){
id = 1;
date = "2020/09/06";
email = "zarezadeh@gmailcom"
});
ml.Add(new MyList(){
id = 2;
date = "2020/09/01";
email = "zarezadeh@gmailcom"
});
List<MyList> New_ml = new Mylist();
foreach (var item in ml)
{
if (New_ml.Where(w => w.email == item.email).SingleOrDefault() == null)
{
New_ml.Add(new MyList()
{
id = item.id,
date = item.date,
email = item.email
});
}
}
在Java中(我认为c#或多或少是相同的):
list = new ArrayList<T>(new HashSet<T>(list))
如果你真的想改变原来的列表:
List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));
list.clear();
list.addAll(noDupes);
为了保持顺序,只需将HashSet替换为LinkedHashSet。
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- 如何读一个文本文件到一个列表或数组与Python
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 返回大列表中每n项的python方式
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new