如何避免列表重复

How avoid duplication in a list

我正在尝试为我的 view.I 获取一个不同的列表,需要从列表中随机 select 记录并将其放入另一个 list.The 以下代码有效..但是它包含重复记录..我怎样才能克服这个问题?

注意:变量"budget"是传入controller的参数,"model1"是PlanObjectsViewModel的List

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() 方法才能使用对象,这一点您当前的代码也应该可以工作。

其实你做对了。对我来说,您似乎没有实现 Equals and GetHashCode,List.Contains 使用它来比较对象。嗯,基本上 GetHashCode 不是强制性的,但如果你实现一个来实现另一个,它是一个很好的设计。

但是您当然可以使用其他答案中指出的 HashSet。