如何避免列表中的重复

时间:2015-05-20 14:05:47

标签: c# random viewmodel

我正在尝试为我的视图提供一个独特的列表。我需要随机选择列表中的记录并将其放入另一个列表。以下代码可以工作..但它包含重复记录..我怎样才能克服这个问题?

注意:变量“budget”是传递给控制器​​的参数,“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);
    }


}

3 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:2)

有两种方法可以执行此操作,使用hashset代替结果列表,或使用Distinct()

HashSet<PlanObjectsViewModel> result

return result.Distinct();

您必须实现Equals()方法才能使用对象,当前代码也应该起作用。

答案 2 :(得分:1)

实际上你已经做到了正确的方法。对我来说,看起来你没有实现EqualsGetHashCode,它们被List.Contains用于比较对象。基本上GetHashCode不是强制性的,但如果你实现了另一个来实现另一个,它是一个很好的设计。

但是当然你可以在其他答案中使用HashSet。

相关问题