tags:

views:

131

answers:

3

I have a List<Order>

public int OrderID { get; set; }
public string CustID { get; set; }
public string Details { get; set; }

I want to write a method that accepts a ID, then searches this List for matching records that have same CustID and returns ORderID and Details in a List<>

+2  A: 

This will get a sequence of Order objects that match the criteria:

var ordersIWant = myList.Where(order => order.CustID == "some customer ID");
Rex M
A: 

Assuming those properties you listed belong to a class.

string searchId="15";

  var list = (from item in myList 
              where item.OrderId == searchId 
              select new {OrderId= item.OrderId,Details = item.Details }).ToList();

Just wrote that without compiling... good luck.

Since you only wanted OrderID and Details I returned an anonymous object. Could also just return item.

Ryu
It should do the trick, and it can be further shortened to `... select new { item.OrderId, item.Details }` - field names will then be automatically generated to be the same as the ones you've specified explicitly in your example.
Pavel Minaev
how do you return anonymous types from a method?
CRice
http://stackoverflow.com/questions/534690/linq-to-sql-return-anonymous-type
CRice
You're right he can't return anonymous type from method. Oh well I solved 99% of his problem, if he can't figure out how to wrap a method around it then tough.
Ryu
+1  A: 
    public List<Order> Get(string id)
    {
        List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it

        var query = from o in orders
                    where o.CustID == id
                    select o;
        return query.ToList();            
    }

Or if you want to specifically return only those two fields maybe something like:

public class Order : IOrderDetails
    {
        public int OrderID { get; set; }
        public string CustID { get; set; }
        public string Details { get; set; }
    }

    public interface IOrderDetails
    {
        int OrderID { get; set; }
        string Details { get; set; }
    }

    public List<IOrderDetails> Get(string id)
    {
        List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it

        var query = from o in orders
                    where o.CustID == id
                    select o as IOrderDetails;
        return query.ToList();
    }
CRice
It's more verbose than the other answers but you have specifically asked to return OrderID and Details in a List<>
CRice