搜索列表<>

时间:2009-10-07 04:02:47

标签: c# linq list search

我有List<Order>

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

我想编写一个接受ID的方法,然后在此List中搜索具有相同CustID的匹配记录,并在List<>

中返回ORderID和Details

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

或者,如果您只想特别返回那两个字段,可能是:

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

答案 2 :(得分:0)

假设您列出的属性属于某个类。

string searchId="15";

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

刚写完就没有编译......祝你好运。

由于您只需要OrderID和Details,我返回了一个匿名对象。也可以返回item