gpt4 book ai didi

c# - 如何避免列表重复

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:40 24 4
gpt4 key购买 nike

我正在尝试为我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com