Jessica
Jessica

Reputation: 3769

How can I select from a collection with LINQ?

I have an IList collection called menuItems.

Here's my MenuItem class:

   public class MenuItem
    {
        public string PartitionKey { get; set; }
        public string RowKey { get; set; }
        public string Order { get; set; }
    }

How can I select the Order from this collection when PartitionKey = "00" and RowKey = "20". Can I use LINQ for this?

Upvotes: 0

Views: 208

Answers (4)

Andrew Barber
Andrew Barber

Reputation: 40160

var result = menuItemsCollection
    .Where(mnu=>mnu.RowKey=="20" && mnu.PartitionKey=="00")
    .Select(mnu=>mnu.Order);

The result of this query will be an IEnumerable<string>, since that's what the Order field is.

The Where() filters the collection down to the items you want. The Select() chooses what is 'returned'. You could choose to compose a completely different object, for example:

var result = menuItemsCollection
    .Where(mnu=>mnu.RowKey=="20" && mnu.PartitionKey=="00")
    .Select(mnu=>
        new SomeOtherClass{Order=mnu.Order, RowKey=mnu.RowKey, RunOn=DateTime.Now});

Upvotes: 2

Maheep
Maheep

Reputation: 5605

Using classes in the System.Linq namespace you can do the following:

var orders = menuItems
    .Where(menuItem=>menuItem.PartitionKey=="00" && menuItem.RowKey=="20")
    .Select(menuItem=> menuItem.Order)

Upvotes: 0

kaj
kaj

Reputation: 5251

Something like:

var orders = from item in menuItems  
where item.PartitionKey == "00" && item.RowKey == "20"  
select new { Order = item.Order};

Try looking at http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b to learn the LINQ basics. It's a very clear set of examples

Upvotes: 0

Smartkid
Smartkid

Reputation: 1842

Yes, you must using "System.Linq" and you will found a group of extensions for your menuitem list.

IList<MenuItem> list = ...
var orders = list.Where(item=>item.PartitionKey=="00" && item.RowKey=="20").Select(item => item.Order);

Upvotes: 0

Related Questions