我已经声明了以下字典,它可以包含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:我只需要第一个列表项为空的项目。以上示例,应该返回“设计师”#39;只有项目。
查询2:如果上面字典中的所有第一个列表项都为空,我也想要数据,请参阅下面的声明:
dictTestdata = new Dictionary<string, List<string>>
{
{ "k1", new List<string> { "", "Programmers" }},
{ "k2", new List<string> { "", "Testers" }},
{ "k3", new List<string> { "", "Designers" }},
};
示例2,应该返回“程序员”,“测试人员”,“设计人员”和“#39;设计师&#39;项目。 如何查询此词典,以便它在问题1和2中返回所需的结果?
答案 0 :(得分: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();
此代码返回:
答案 1 :(得分:0)
这是一个可能的解决方案:
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);
答案 2 :(得分:0)
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();
}