开发者

Linq Query to IEnumerable<T> Extension Method

Consider this,

     class Item
     { 
        public string ID { get; set;}
        public string Description { get; set; }
     }

     class SaleItem
     { 
        public string ID { get; set;}
        public s开发者_如何学运维tring Discount { get; set; }
     }


     var itemsToRemoved = (List<Item>)ViewState["ItemsToRemove"];
     // get only rows of ID
     var query = from i in itemsToRemoved select i.ID;

     var saleItems= (List<SaleItem>)ViewState["SaleItems"];
     foreach (string s in query.ToArray())
     {
            saleItems.RemoveItem(s);
     }

How can I write this LINQ phrase using IEnumerable/List Extension methods

  // get only rows of ID
   var query = from i in items select i.ID;

thanks in advance.


That one's easy:

var query = items.Select(i => i.ID);

A select clause always corresponds to a call to Select. Some of the other operators end up with a rather more complex expansion :) If you work hard, you can get the compiler to do some very odd stuff...

You can find all the details of this and other query expression translations in section 7.16 of the C# specification (v3 or v4).

<plug> You could also buy C# in Depth, 2nd edition and read chapter 11 if you really wanted to :)</plug>


You can use this:

var query = items.Select(i => i.ID);

A couple of other points:

Here you don't need the call to ToArray:

foreach (string s in query.ToArray())

Also if your list is large and you are removing a lot of items you may want to use List.RemoveAll instead of iterating. Every time you remove an item from a list all the other items after it have to be moved to fill the gap. If you use RemoveAll this only has to be done once at the end, instead of once for every removed item.

List<Item> itemsToRemove = (List<Item>)ViewState["ItemsToRemove"];
HashSet<string> itemIds = new HashSet<string>(itemsToRemove.Select(s => s.ID));
saleItems.RemoveAll(c => itemIds.Contains(c.ID));


public static class ItemCollectionExtensions
{
    public static IEnumerable<int> GetItemIds(this List<Item> list)
    {
        return list.Select(i => i.ID);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜