[英]Find value from Dictionary where value property is null using C# LINQ
In the below code, the dictionary will have a lot of Person data, with some missing information about Name property.在下面的代码中,字典将包含大量 Person 数据,其中缺少一些有关 Name 属性的信息。 I need to get the list of Person ID s, where the Name property is Null or Empty.
我需要获取 Person ID的列表,其中Name属性是 Null 或 Empty。
Note: I am expecting List for the missing Names注意:我期待缺少名称的列表
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
public int Age {get; set;}
}
public class Persons
{
private Dictionary<int, Person> m_dic =new Dictionary<int, Person>();
public Dictionary<int, Person> Data
{
get { return m_dic; }
}
public void AddData()
{
//Code to fill m_dic
m_dic.Add(1, new Person() {101, "John", 30 });
m_dic.Add(2, new Person() {102, "", 40 });
m_dic.Add(3, new Person() {103, "Peter", 20 });
m_dic.Add(4, new Person() {104, "", 46});
}
public List<int> FindData()
{
var list = from p in m_dic
where p.Value.Name == Null
select new { p.value.Id };
return list;
}
}
So the output will have List with values like 102, 104. Need to improve the LINQ query.因此 output 将具有值如 102、104 的 List。需要改进 LINQ 查询。 Can someone help?
有人可以帮忙吗?
You can use .Where()
clause to filter dictionary elements based on condition and use .Select()
to get list of Ids
,您可以使用
.Where()
子句根据条件过滤字典元素并使用.Select()
获取Ids
列表,
var result = m_dic
.Where(x => String.IsNullOrEmpty(x.Value.Name)) //Filter where name is null or empty
.Select(y => y.Value.Id) //Get only Ids
.ToList();
where string.IsNullOrEmpty(p.Value.Name)
instead of where p.Value.Name == Null
.where string.IsNullOrEmpty(p.Value.Name)
而不是where p.Value.Name == Null
。 So it will handle null
value as well as blank ""
.null
值以及空白""
。select
statement and not use new {... }
because it will create IEnumerable<Object>
not IEnumerable<int>
.select
语句并且不使用new {... }
因为它会创建IEnumerable<Object>
而不是IEnumerable<int>
。 You can just use select p.Value.Id
to return list of id
s.select p.Value.Id
返回id
的列表。return list.ToList();
return list.ToList();
so it will convert IEnumerable<int>
to List<int>
.IEnumerable<int>
转换为List<int>
。 Updated function will be like below.更新后的 function 如下所示。
public static List<int> FindData()
{
var list = from p in m_dic
where string.IsNullOrEmpty(p.Value.Name)
select p.Value.Id;
return list.ToList();
}
Why don't you use Lambda expression in your find function.为什么不在你的查找 function 中使用 Lambda 表达式。 I'm rewriting your function with lambda.
我正在用 lambda 重写你的 function。
public List<int> FindData()
{
var list = m_dic.Where(x => x.Value.Name.Equals("")).Select(x => x.Value.Id).ToList();
return list;
}
You'll get your desired result.你会得到你想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.