gpt4 book ai didi

c# - 从字典<>中以文化不变/大小写不变的方式寻找值(value)<>

转载 作者:行者123 更新时间:2023-11-30 18:48:03 24 4
gpt4 key购买 nike

如果我有这样的字典

Dictionary<string, List<string>> cars = new Dictionary <string,List<string>>();

'importcar', ['audi', 'bmw', 'mercedes']
'domesticcar', ['chevy', 'mustang']
'truck', ['ford', 'gmc', 'chevy', 'toyota']

如何检查此字典的列表值中是否包含字符串?

对于上面的例子,我如何在 InvariantCulture 和 Ignored 的情况下检查这个字典是否有字符串 'chevy'(在上面的例子中,它有键 'domesticcar' 和 'truck')?

我试过了,虽然它有效,但它似乎并不优雅

// this will search for a car in dictionary under any key and find 1st occurance of it
// of it and remove it. If List for the key is empty, it will remove the key as well.
foreach (var k in cars.Keys)
{
bool found = false;

List<string> ls = cars[k]; // get List for key
if (ls.Contains("chevy", StringComparer.InvariantCultureIgnoreCase))
{
// get first occurance of car and remove it if found in list
var car = ls.FirstOrDefault(c => c.Trim().ToLowerInvariant() == "chevy".Trim().ToLowerInvariant());
if (car != null)
{
found = true; //found 1st occurance of car in Dictionary, flag to exit loop
ls.Remove(car);
}
}
// remove key if its List<string> is empty
if (ls.Count == 0)
{
cars.Remove(k);
}

if (found) break;
}

最佳答案

你可以这样使用contains:

var keys = cars.Where(c => c.Value.Contains("chevy", StringComparer.InvariantCultureIgnoreCase)).Select(a => a.Key);

//编辑:我得到了反对票?当然你可以使用修剪:

public static IEnumerable<string> GetKeys(Dictionary<string, List<string>> storage, string car)
{
return storage.Where(c => c.Value.Contains(car.Trim(), StringComparer.InvariantCultureIgnoreCase)).Select(a => a.Key);
}

关于c# - 从字典<>中以文化不变/大小写不变的方式寻找值(value)<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597895/

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