2017-02-15 94 views
3

我有一個類比較2列出了用null值

public class User 
{ 
    public int id { get; set; } 
    public string code { get; set; } 
} 

之一,我想用一個特定的代碼值

List<User> users = new List<User>(); 

users.Add(new User() { id = 1, code="A"}); 
users.Add(new User() { id = 2, code = null }); 
users.Add(new User() { id = 3, code = "C" }); 
users.Add(new User() { id = 4, code = "C" }); 
users.Add(new User() { id = 5, code = "B" }); 

string[] possibleValues = new string[] { null, "A", "B" }; 

var result = users 
    .Where(u => possibleValues 
       .Any(l => l.Equals(u.code))) 
    .ToList(); 

我得到NullReferenceException因爲possibleValues在有null找到用戶它。我明白那個。有人可以提出一個更好的方法來做到這一點。

+0

在這裏,您可以簡單地使用'=='運算符。當查看[String code](https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs)時,== ==運算符具有以下代碼:'public static bool operator = =(String a,String b){0}返回String.Equals(a,b); }'。所以這個代碼'possibleValues.Any(l => l == u.code)'將會工作得很好。 – dee

+0

是的,我同意你的意見。在看完德米特里的回答後,我明白了這一點。然而。我更喜歡他的回答,因爲這給了我靈活地添加StringComparison.OrdinalIgnoreCase – Rajat

+0

好吧,在這種情況下,您確實需要直接調用'string.Equals'靜態方法,因爲'string'上的'=='運算符執行一個序數敏感和文化不敏感)的比較。 – dee

回答

3

你比較string動手清除空值,這是whay我建議改變l.Equals(...)string.Equals(...)一個知道如何處理null S:

... 
    // string.Equals(l, u.code): 
    // do l and u.code equal? i.e. are they both nulls 
    // or do they contain the equal strings 
    var result = users 
    .Where(u => possibleValues.Any(l => string.Equals(l, u.code))) 
    .ToList(); 

請,通知,你可以調string.Equals如果你想,如 string.Compare(l, u.code, StringComparison.OrdinalIgnoreCase)

0

您可以嘗試object.ReferenceEquals而不是l.Equals。在你的情況下,當迭代中l爲空時,它不包含.Equals()的定義並導致錯誤。您可以通過下面的代碼嘗試相同:

users.Where(u => possibleValues.Any(l => object.ReferenceEquals(l,u.code))).ToList(); 

上面的代碼會給你的ID 1,在本例中25的項目。

+0

讚賞投票,謝謝 –

+0

爲什麼投票棄權。我實際上正在考慮使用@RajatMalik這個 – Rajat

+0

:通常我會因個人報復而陷入困境,忘記這一點。很高興爲您提供 –

1

您可以使用WhereAny和添加過濾器忽略這樣值: -

var result = users.Where(x => possibleValues 
       .Any(z => z == x.code && (z != null || x.code != null))); 

UPDATE:

根據與@Dmitry(討論這對我來說很有意義)你可以這樣簡化: -

var result = users.Where(x => possibleValues.Any(z => z == x.code)); 

Working Fiddle.

+0

希望他在'possibleValues'中包含'null'以獲得結果爲id爲'2'的項目但是您的代碼不包括輸出 –

+0

@ un-lucky - 但OP從未提及過,如果他真的想要'2'。雖然它需要一個小小的修復:'x.code == null'而不是'x.code!= null' :) –

+0

我們不是要獲得* three *'user's,而不是* two * with code' 「A」,「B」和** null **?只有代碼爲'2'時,您的小提琴演示纔會返回代碼'1'和'5'。 –

0

嘗試這個U可以從這個代碼

var result = users.Where(y=> possibleValues 
       .Any(u => u == y.code && (u != null || y.code != null))); 
+0

''' z'與'u'與Rahul的答案有什麼不同? –

+1

你是否因爲他的評論而冷靜下來?不道德。 – Berkay

+0

@Berkay:聽起來沒錯,但是誰知道真相 –