Basic LINQ expression for an ItemCollection

前端 未结 2 1737
盖世英雄少女心
盖世英雄少女心 2021-02-05 00:20

I have an ItemCollection that I\'d like to query using LINQ. I tried the following (contrived) example:

var lItem =
    from item in lListBox.Items
    where Str         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 00:34

    It's because ItemCollection only implements IEnumerable, not IEnumerable.

    You need to effectively call Cast() which is what happens if you specify the type of the range variable explicitly:

    var lItem = from object item in lListBox.Items
                where String.Compare(item.ToString(), "abc") == 0
                select item;
    

    In dot notation, this is:

    var lItem = lListBox.Items
                        .Cast()
                        .Where(item => String.Compare(item.ToString(), "abc") == 0));
    
    
    

    If course, if you have a better idea of what's in the collection, you could specify a more restrictive type than object.

    提交回复
    热议问题