创建具有子类型限制的linq表达式

| 我有此类型
IEnumerable<MyBaseType>
的列表,我正尝试为此创建一个额外的地方条款来检索列表中的特定项目。该特定值仅存在于子类型MyFirstType和MySecondType上。不在MyBaseType上。 是否可以创建一种表达...
MyList.Where(b => (b is MyFirstType || (b is MySecondType)) && b.SpecificValue == message.SpecificValue);
上面的方法不起作用,因为b的类型为MyBaseType,并且那里不存在SpecificValue。还要注意,我确实有另一个子类型MyThirdType,它们都没有SpecificValue。 做我想做的是什么...
foreach (dynamic u in MyList)
{
    if (u is MyFirstType || u is MySecondType)
    {
        if (u.SpecificValue == message.SpecificValue)
        {
            //Extracted code goes here
            break;
        }
    }
}
任何人都有一个想法如何为上述情况创建linq表达式?     
已邀请:
        您的代码直接翻译成Linq where子句是
string messageValue = \"foo\";
var result = baseList.Where(item =>
{
    dynamic c = item;
    if(item is MyFirstType || item is MySecondType)
    {
        if( c.SpecificValue == messageValue)
            return true;
    }
    return false;
});
这将需要测试类的类型并使用动态-因此您最好直接将项目转换为
MyFirstType
MySecondType
。 一种替代方法是使用反射来检查属性是否存在,使用这种方法,只要项目确实具有您感兴趣的属性,您就不必依赖它们的实际类型:
string messageValue = \"foo\";
var result = baseList.Where( item => 
    {
        var prop =  item.GetType().GetProperty(\"SpecificValue\");
        if (prop != null && prop.GetValue(item, null) == messageValue)
            return true;
        else return false;
    });
如果可以选择修改类层次结构,则可以让
MyFirstType
MySecondType
实现保存属性的接口,然后可以在Linq查询中使用
OfType()
interface ISpecific
{
    string SpecificValue { get; set; }
}
class MyFirstType : MyBase, ISpecific
{
    public string SpecificValue { get; set; }
}
...
string messageValue = \"foo\";
var result = baseList.OfType<ISpecific>()
                     .Where(item => item.SpecificValue == messageValue);
    
        也许有一个更好的解决方案,但是就我所知,这可能效果很好...如果您不介意性能的话。 好了,首先声明一个接口:
public interface IMySpecialType
{
   object SpecificValue {get; set;} //you didn\'t specify what type this is
   //all your other relevant properties which first and second types have in common
}
然后,使MyFirstType和MySecondType从此接口派生:
public class MyFirstType : MyBaseType, IMySpecialType
{
   //snipet
}

public class MyFirstType : MySecondType, IMySpecialType
{
   //snipet
}
然后,过滤并强制转换:
MyList
    .Where(b => (b is MyFirstType) || (b is MySecondType))
    .Cast<IMySpecialType>()
    .Where(b => b.SpecificValue == message.SpecificValue);
    //do something
    
        一种更简单的方法是创建一个接口,以标记所有具有此属性SpecificValue的类。然后这是一个儿童游戏:
    static void Main(string[] args)
    {
        List<MyBaseType> MyList = new List<MyBaseType>();
        ISpecificValue message = new MyFirstType();
        MyList.OfType<ISpecificValue>().Where(b => b.SpecificValue == message.SpecificValue);
    }
}

class MyBaseType { }
interface ISpecificValue { string SpecificValue { get; set; } }
class MyFirstType : MyBaseType, ISpecificValue
{
    public string SpecificValue;
}
class MySecondType : MyBaseType, ISpecificValue
{
    public string SpecificValue;
}
    

要回复问题请先登录注册