简体   繁体   中英

linq 'where' with using reflection doesn't work

I'm trying to get items with using linq and reflection:

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

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:

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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