3

How can I convert IEnumerable<object> to List<IFoo> where each object is an IFoo?

I have an IEnumerable<object>, someCollection, and each item in someCollection is an IFoo instance. How can I convert someCollection into a List<IFoo>? Can I use convert or cast or something instead of looping through and building up a list?


<div class="iphone"></div>
<div class="screen"></div>
<ul>
<li class="screenshots"><a href="#" id="scr1">Screen 1</a></li>
<li class="screenshots"><a href="#" id="scr2">Screen 2</a></li>
</ul>
<script>
$('.screenshots a').click(function(){
    switch($(this).attr('id')){
        case 'src1':
            $('.iphone').css('background-image','url("image1.png")');
        break;
        case 'src2':
            $('.iphone').css('background-image','url("image2.png")');
        break;
    }
});
</script>
4

3 に答える 3

13

LINQ を使用すると、 を使用しCastてアイテムをキャストし、 を使用ToListしてリストを取得できます。

試す:

 IEnumerable<object> someCollection; //Some enumerable of object.
 var list = someCollection.Cast<IFoo>().ToList();
于 2012-06-01T18:56:30.540 に答える
4

Try this:

enumerable.Cast<IFoo>().ToList();
于 2012-06-01T18:56:03.940 に答える
4

someCollection.Cast<IFoo>().ToList()

于 2012-06-01T18:56:15.583 に答える