简体   繁体   中英

searching a List<>

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

这将获得符合条件的一系列Order对象:

var ordersIWant = myList.Where(order => order.CustID == "some customer ID");
    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();
    }

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM