c# - 如何避免列表重复

标签 c# random viewmodel

我正在尝试为我的 View 获取一个不同的列表。我需要从一个列表中随机选择记录并将其放入另一个列表中。以下代码有效..但它包含重复记录..我该如何克服这个问题?

注意:变量“budget”是传递给 Controller ​​的参数,“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

关于c# - 如何避免列表重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352076/

相关文章:

python - 使用 numpy/scipy 在 python 中均匀有效地采样整数

python - Randrange 依赖于变量 - Python

android - ViewModel 的 LiveData 是否可以包含供其各自 View 调用的函数?

c# - 使用哪个 C# 多线程选项

c# - 许多 WebReferences 使用相同的类

c# - 使用 linq 列表中前 3 项的平均值

java - java中从List中随机选择一个对象

c# - MVVM ViewModel 到模型通信和参数

javascript - knockout 复选框选择过滤器

javascript - MVC5 上的掩码输入