如何避免列表中的重复
本文关键字:何避免 列表 | 更新日期: 2023-09-27 17:50:09
我试图得到一个不同的列表到我的视图。我需要从列表中随机选择记录,并将其放入另一个列表。下面的代码可以工作,但是它包含重复的记录,我该如何解决这个问题?
注意:变量"预算"是传递给控制器的参数,"model1"是PlanObjectsViewModel的列表
int count = 0;
foreach (var item in model1) { count++; }
List<PlanObjectsViewModel> result = new List<PlanObjectsViewModel>();
Random rand = new Random();
double? temp=0;
while(budget>temp)
{
int randi = rand.Next(0, count);
var nthItem = model1.OrderBy(p => p.Id).Skip(randi).First();
temp += nthItem.Price;
if (!result.Contains(nthItem)) // Think this is the wrong point
{
result.Add(nthItem);
}
}
使用HashSet<PlanObjectsViewModel>
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Input array that contains three duplicate strings.
string[] array1 = { "cat", "dog", "cat", "leopard", "tiger", "cat" };
// Display the array.
Console.WriteLine(string.Join(",", array1));
// Use HashSet constructor to ensure unique strings.
var hash = new HashSet<string>(array1);
// Convert to array of strings again.
string[] array2 = hash.ToArray();
// Display the resulting array.
Console.WriteLine(string.Join(",", array2));
}
}
输出:cat,dog,cat,leopard,tiger,cat
cat,dog,leopard,tiger
有两种方法可以做到这一点,使用hashset
代替列表的结果,或使用Distinct()
HashSet<PlanObjectsViewModel> result
或
return result.Distinct();
您将不得不实现Equals()方法来处理对象,这一点您当前的代码也应该工作。
实际上你的做法是正确的。对我来说,它看起来像你没有实现等号和GetHashCode是由列表使用。包含用于比较对象。基本上GetHashCode不是强制性的,但如果你实现一个来实现另一个,它是一个很好的设计。
当然,你也可以使用HashSet作为其他答案。