使用LINQ获取特定子类型的列表条目

时间:2016-12-10 18:47:53

标签: c# linq collections ienumerable

我有三个班级:Foo,Bar和Baz。 Bar和Baz都扩展了Foo,这是抽象的。我有一个类型Foo的列表,充满了酒吧和Bazes。我想使用LINQ Where子句返回所有类型。类似的东西:

parse(text, {skip_empty_lines: true}, function(err, data){

    data.forEach( function(row) {
        console.log ('Logging from within parse function:');
        console.log ('URL: '+row[0]+'\n');

        let url = row[0];

        request(url, function(error, response, body) {
            console.log ('Logging from within request function:');
            console.log('Loading URL: '+url+'\n');
            if (!error && response.statusCode == 200) {
                if (r_isnyt.exec(body)){ 
                    console.log('This is the NYT site! ');
                }
                console.log ('');
            }
        });         
    });
});

当我这样做时,我收到一个错误:附加信息:无法转换'WhereListIterator class Bar : Foo { public Bar() { } } class Baz : Foo { public Baz() { } } List<Foo> foos = new List<Foo>() { bar1, bar2, foo1, foo2, bar3 }; List<Bar> bars; bars = (List<Bar>)foos.Where(o => o.GetType() == Type.GetType("Bar")); 1 [Bar]'类型的对象。

1 个答案:

答案 0 :(得分:6)

尝试OfType():过滤掉Bar项并将其具体化为列表:

List<Bar> bars = foos
  .OfType<Bar>()
  .ToList();

修改:如果您只想要Bar个实例,而不是Baz,即使/ Baz来自Bar,您必须添加一个条件:

List<Bar> bars = foos
  .OfType<Bar>()
  .Where(item => item.GetType() == typeof(Bar)) // Bar only
  .ToList();