简体   繁体   English

LINQ 查询中的属性反射未按预期运行

[英]Property reflection inside of a LINQ query doesn't behave as expected

Given the following lines of code in C#:鉴于 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();

result obviously contains a collection of objects.结果显然包含一组对象。 The first line gives me a value (46ee6799-2bed-4a7a-93f8-0839affbd218).第一行给了我一个值 (46ee6799-2bed-4a7a-93f8-0839affbd218)。 However, the second line returns 0 objects in the list.但是,第二行在列表中返回 0 个对象。 The first line confirms that the first object in the collection does have the value I'm filtering on in the second line, while the second line tells me that no objects in the collection has that value on the property I'm checking.第一行确认集合中的第一个对象确实具有我在第二行过滤的值,而第二行告诉我集合中没有对象在我正在检查的属性上具有该值。 Can someone explain why this does not work?有人可以解释为什么这不起作用吗? And potentially provide an alternative?并可能提供替代方案?

Since ?.GetValue(x, null) returns instance of object , when you compare it with "46ee6799-2bed-4a7a-93f8-0839affbd218" you compare references , not values :由于?.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");

Outcome:结果:

Not Equal
Equal

Use string.Equals instead of == in order to compare values :使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM