[英]Find value from Dictionary where value property is null using C# LINQ
在下面的代碼中,字典將包含大量 Person 數據,其中缺少一些有關 Name 屬性的信息。 我需要獲取 Person ID的列表,其中Name屬性是 Null 或 Empty。
注意:我期待缺少名稱的列表
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;
}
}
因此 output 將具有值如 102、104 的 List。需要改進 LINQ 查詢。 有人可以幫忙嗎?
where string.IsNullOrEmpty(p.Value.Name)
而不是where p.Value.Name == Null
。 因此它將處理null
值以及空白""
。select
語句並且不使用new {... }
因為它會創建IEnumerable<Object>
而不是IEnumerable<int>
。 您可以只使用select p.Value.Id
返回id
的列表。return list.ToList();
因此它將IEnumerable<int>
轉換為List<int>
。更新后的 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();
}
為什么不在你的查找 function 中使用 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;
}
你會得到你想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.