具有列表<字符串>作为值的 C# 搜索字典
本文关键字:搜索 字典 列表 字符串 | 更新日期: 2023-09-27 17:55:19
我已经声明了以下字典,它可以包含10个以上的项目:
Dictionary<string, List<string>> dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "1", "Programmers" }},
{ "k2", new List<string> { "3", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
查询 1:我只需要第一个列表项为空的那些项目。上面的示例,应仅返回"设计器"项。
查询 2:如果上述字典中的所有第一个列表项都为空,我也想要数据,请参阅下面的声明:
dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "", "Programmers" }},
{ "k2", new List<string> { "", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
示例 2,应返回"程序员"、"测试人员"、"设计器"项。如何查询此字典,以便它在问题 1 和 2 中返回所需的结果?
Dictionary<string, List<string>> dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "1", "Programmers" }},
{ "k2", new List<string> { "3", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
{ "k4", new List<string> { "", "Designers2" }},
};
var query = from item in dictTestdata
where String.IsNullOrWhiteSpace(item.Value.First())
select item.Value.Where(v => !String.IsNullOrWhiteSpace(v));
query.SelectMany (q => q, (a, b) => b).Dump();
此代码返回:
- 设计师
- 设计师2
static void Main(string[] args)
{
Dictionary<string, List<string>> dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "1", "Programmers" }},
{ "k2", new List<string> { "3", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
var data = dictTestdata.Values.Where(m => string.IsNullOrEmpty(m.ElementAtOrDefault(0)));
foreach (List<string> item in data)
{
Console.WriteLine(item.ElementAtOrDefault(1));
}
dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "", "Programmers" }},
{ "k2", new List<string> { "", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
data = dictTestdata.Values.Where(m => string.IsNullOrEmpty(m.ElementAtOrDefault(0)));
foreach (List<string> item in data)
{
Console.WriteLine(item.ElementAtOrDefault(1));
}
Console.Read();
}
这是一个可能的解决方案:
Dictionary<string, List<string>> dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "1", "Programmers" }},
{ "k2", new List<string> { "3", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
var result1 = dictTestdata.Where(kvp => string.IsNullOrWhiteSpace(kvp.Value[0]))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "", "Programmers" }},
{ "k2", new List<string> { "", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
var result2 = dictTestdata.Where(kvp => string.IsNullOrWhiteSpace(kvp.Value[0]))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);