簡體   English   中英

C#LINQ-獲取對,當在所有具有相同第一個值的對中第二個值為null時

[英]C# LINQ - Get pairs, when second value is null in all pairs that have the same first value

假設我有這樣的配對(在列表中):[{a,15},{b,null},{a,null}]

每對都有一個字符鍵和一個可為空的值。 我想選擇列表中不包含具有相同鍵和非空值的另一對的所有對。

在上面的示例列表中,我只想獲取{b,null},因為'a'在第一對中具有非null值。 我將如何使用LINQ做到這一點?

假設list(變量名稱項)是(chr,Id)的集合,然后使用以下linq獲取結果

        var result = (from t1 in items
                      group t1 by t1.chr into t2
                      where t2.Count(p => p.Id!= null) == 0
                      select new
                      {
                          chr = t2.Key,
                          Id  = t2.Select(p => p.Id).FirstOrDefault()
                      }).ToList();

您可以使用Where函數來選擇元素,而使用Any函數來檢查是否存在具有相同鍵值和非null值的對。 這是一個例子:

class Pair
{
    public char Key { get; set; }
    public int? Value { get; set; }
}

var pairs = new[] { new Pair { Key = 'a', Value = 15 },
                    new Pair { Key = 'b', Value = null },
                    new Pair { Key = 'a', Value = null }
}

var nullOnlyPairs = pairs.Where(p => !pairs.Any(a => a.Key == p.Key && a.Value != null));

假設您的列表項具有兩個字段(鍵,值),則可以執行此操作。

var output = items.GroupBy(c=>c.Key) // Group by Letter
                  .Where(c=>!c.Any(e=>e.Value != null)) // Verify each Key has any other value than Null
                  .Select(c=>c.First());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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