简体   繁体   English

使用反射的 linq 'where' 不起作用

[英]linq 'where' with using reflection doesn't work

I'm trying to get items with using linq and reflection:我正在尝试使用 linq 和反射来获取项目:

var type = "Home";
var list = new List<object>();
... some initialization
var selectedItems = list.Where(x => x.GetType().GetProperty("Type").GetValue(x) == type);

into selectedItems I want to get 2 items (that matches condition), but I get one进入selectedItems我想得到 2 个项目(符合条件),但我得到一个

What's wrong in this code?这段代码有什么问题? Thanks in advance提前致谢

If you are trying to find list elements of a given type, you just need to compare to the type's full name:如果您尝试查找给定类型的列表元素,您只需与该类型的全名进行比较:

var selectedItems = list.Where(x => (string)x.GetType().FullName == type);

If instead you want to query a property of classes in the list called Type, your existing code works:相反,如果您想查询名为 Type 的列表中的类属性,您现有的代码可以工作:

var type = "Home";
var list = new List<object>()
{
    new Home(),
    new Business()
};

abstract public class Base
{
    public abstract string Type { get; }
}

public class Home : Base
{
    public override string Type => "Home";
}

public class Business : Base
{
    public override string Type => "Business";
}

// This works (you have to cast GetValue() to string)
var selectedItems = list.Where(x => (string)x.GetType().GetProperty("Type").GetValue(x) == type);

If this is your scenario and the property in question is not public, change如果这是您的方案并且相关属性未公开,请更改

GetProperty("Type")

to

GetProperty("Type", BindingFlags.NonPublic | BindingFlags.Instance)

I just needed to cast properties to one type:我只需要将属性转换为一种类型:

var selectedItems = list.Where(x => Equals(x.GetType().GetProperty("Type").GetValue(x), type))

The question is hardly clear but probably you want this?:这个问题很难说清楚,但可能你想要这个?:

var list = new List<object>();
var selectedItems = list.OfType<Home>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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