CSharpNoob
CSharpNoob

Reputation: 1301

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 string 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.

Upvotes: 3

Views: 18241

Answers (3)

Mark Byers
Mark Byers

Reputation: 838106

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));

Upvotes: 4

James
James

Reputation: 82096

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500165

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>

Upvotes: 5

Related Questions