简体   繁体   English

如何避免列表重复

[英]How avoid duplication in a list

I'm trying to get a distinct list to my view.I need to select records from a list randomly and put it in to another list.The following code works..But it contain duplication records..How can I overcome this problem? 我正在尝试查看一个不同的列表。我需要从一个列表中随机选择记录,然后将其放入另一个列表。以下代码有效。但是它包含重复记录。如何解决此问题?

Note: the variable "budget" is a parameter passed in to the controller and "model1" is a List of PlanObjectsViewModel 注意:变量“ 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);
    }


}

Use a HashSet<PlanObjectsViewModel> 使用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));
    }
}

Output: 输出:

cat,dog,cat,leopard,tiger,cat
cat,dog,leopard,tiger

there are two ways to do this, use a hashset instead of list for your result, or use Distinct() 有两种方法可以执行此操作,可以使用hashset代替结果列表,也可以使用Distinct()

HashSet<PlanObjectsViewModel> result

or 要么

return result.Distinct();

You will have have to implement the Equals() method for this to work with objects, a which point your current code should work too. 您必须实现Equals()方法才能与对象一起使用,这一点您当前的代码也应该起作用。

Actually you have made it the correct way. 实际上,您已经做到了正确的方法。 For me it looks like you didnt implemented Equals and GetHashCode which are used by List.Contains to compare objects. 对我来说,您似乎没有实现List.Contains用来比较对象的EqualsGetHashCode Well basically GetHashCode is not mandatory but its a good design if you implemented the one to implement the other one. 好吧,基本上,GetHashCode不是强制性的,但是如果您实现了一个实现另一个,则它是一个很好的设计。

But ofcourse you can use HashSet as pointed in the other answeres. 但是,当然,您可以使用其他答案中指出的HashSet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM