簡體   English   中英

使用 C# LINQ 從字典中查找值屬性為 null 的值

[英]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()子句根據條件過濾字典元素並使用.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();
  1. 您應該檢查where string.IsNullOrEmpty(p.Value.Name)而不是where p.Value.Name == Null 因此它將處理null值以及空白""
  2. 更新select語句並且不使用new {... }因為它會創建IEnumerable<Object>而不是IEnumerable<int> 您可以只使用select p.Value.Id返回id的列表。
  3. 在 return 語句中使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM