[英]Property reflection inside of a LINQ query doesn't behave as expected
鑒於 C# 中的以下代碼行:
var testvalue = result[0]
.GetType()
.GetProperty(propertyNameToFilterOn)
.GetValue(result[0], null);
var test = result
.Where(x => x
.GetType()
.GetProperty(propertyNameToFilterOn)
?.GetValue(x, null) == "46ee6799-2bed-4a7a-93f8-0839affbd218")
.ToList();
結果顯然包含一組對象。 第一行給了我一個值 (46ee6799-2bed-4a7a-93f8-0839affbd218)。 但是,第二行在列表中返回 0 個對象。 第一行確認集合中的第一個對象確實具有我在第二行過濾的值,而第二行告訴我集合中沒有對象在我正在檢查的屬性上具有該值。 有人可以解釋為什么這不起作用嗎? 並可能提供替代方案?
由於?.GetValue(x, null)
返回object
實例,當您將它與"46ee6799-2bed-4a7a-93f8-0839affbd218"
進行比較時,您比較的是引用,而不是值:
string st = "46ee6799-2bed-4a7a-93f8-0839affbd218";
// Some manipulations (we don't want the compiler to intern strings)
object o = (st + " ").Trim();
Console.WriteLine(o == st ? "Equal" : "Not Equal");
Console.WriteLine(string.Equals(o, st) ? "Equal" : "Not Equal");
結果:
Not Equal
Equal
使用string.Equals
而不是==
來比較值:
var test = result
.Where(x => string.Equals(x
.GetType()
.GetProperty(propertyNameToFilterOn)
?.GetValue(x, null), "46ee6799-2bed-4a7a-93f8-0839affbd218"))
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.