gpt4 book ai didi

c# - 包含二维集合中的方法

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:46 25 4
gpt4 key购买 nike

如何通过“Name”字段比较 cars 数组中的 auto[0]?字符串 if (!cars.Contains(auto[0])) 当然不正确。


namespace AutoSqare
{
class CarsInfo
{
static List<Tech> cars = new List<Tech>();
public class Tech
{
public string Name { get; set; }
public double KM { get; set; }
}
static void Main()
{
string[] auto = new string[]{"Lada Vesta"};
cars.Add(new Tech()
{
Name = "Lada Vesta Sport",
KM = 190
});

if (!cars.Contains(auto[0]))
cars.Add(new Tech()
{
Name = auto[0],
KM = 0
});

}
}
}

最佳答案

您可以使用 LINQ 的 Any()方法:

if (!cars.Any(c => c.Name == auto[0]))

但是您似乎打算只使用唯一 汽车名称,所以使用 Dictionary<string,Tech>似乎比 List<Tech> 好:

static Dictionary<string, Tech> cars = new Dictionary<string,Tech>();

static void Main()
{
string[] auto = new string[]{"Lada Vesta"}; // <-- you also had a syntax error here
Tech tech = new Tech()
{
Name = "Lada Vesta Sport",
KM = 190
};
cars.Add(tech.Name, tech);

if (!cars.ContainsKey(auto[0])) // <--- Use ContainsKey here
cars.Add(auto[0], new Tech()
{
Name = auto[0],
KM = 0
});
}

关于c# - 包含二维集合中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128165/

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