C#Linq选择并强制转换无错误

时间:2018-07-05 15:49:03

标签: c# linq

有没有一种更干净的方法来获取吠叫的狗的名单?

public abstract class Mammal
{
    public bool sweat_glands;
    public bool is_aquatic;
}
public class Whale: Mammal
{
    public Whale() { is_aquatic = true; }
}
public class Dog: Mammal
{
    public bool Barks { get; set; }
    public Dog() { is_aquatic = false; }
}
class Program
{        
    static void Main(string[] args)
    {
        List<Mammal> mammals = new List<Mammal>();
        mammals.Add(new Whale());
        mammals.Add(new Dog() { Barks = false });
        List<Dog> dogs = (from c in mammals where c is Dog && ((Dog)c).Barks.Equals(true) select c).Cast<Dog>().ToList();
    }
}

如果执行以下操作,则会在最后一行得到编译错误:为源类型IEnumerable找到了查询模式的多个实现。选择不明确。

List<Dog> dogs = (from c in mammals where c is Dog && ((Dog)c).Barks.Equals(true) select (Dog)c).ToList();

谢谢!

2 个答案:

答案 0 :(得分:4)

您的代码对我来说很好。您可以使用OfType对其进行简化:

var dogs = mammals
    .OfType<Dog>()
    .Where(d => d.Barks);

答案 1 :(得分:1)

无需一口气做完整个事情,这会造成混乱。

List<Dog> dogs = (from c in mammals 
                  let d = (c as Dog)
                  where 
                     d != null && d.Barks
                  select d
                 ).ToList();