使用Linq从列表中筛选列表

时间:2014-03-21 09:07:51

标签: c# asp.net linq list

我检索了150条记录的特定类列表。 现在,我只想要那些具有Licenseid的记录,这些记录在我的另一个int List中。

例如My MainList

List<CustomerDocument> _list = GetListByID(CustomerID);

在此列表中,我有列LicenseID,CustomerID,CustomerName,Type,Age e.t.c

和SecontList

List<int> type = new List<int>();

在Int列表中,我动态地逐个添加LicenseID。

Public class CustomerDocument
{
 public int LicenseID{get;set;};
 public int CustomerID{get;set;};
 public string CustomerName{get;set;};
 public int Age{get;set;};
}

这是我正在获取列表的CustomerDocument类。

This is my debug at solution

现在假设,如果Int列表有三条记录,那么我希望我的主列表中的那些记录在我的Int列表中使用Linq具有这三个LicenseID。

_list = ??? 



 List<CustomerDocument> list = new List<CustomerDocument>();
 List<Int> types = new List<Int>();
 MapSearchSalesEntities datacontext = new MapSearchSalesEntities();

 var collection = ddlLicenseType.CheckedItems;
 if (collection.Count > 0)
        {
            foreach (var item in collection)
            {
                int value = Convert.ToInt32(item.Value);
                types .Add(value);
            }
        }

var query = (from t1 in datacontext.Licenses 
              select new CustomerDocument
                   {
                       LicenseID = t1.LicenseID,
                       CustomerID = t1.CustomerID,
                       CustomerName= t1.CustomerName,
                       Age= t1.Age,
                     });
list = query.ToList(); ---gives 150 Records

  if (types != null && types.Count > 0)
  {
   list = list.Where(c => types.Contains(c.LicenseID)).ToList(); --- Gives 0 Records
  }

enter image description here

3 个答案:

答案 0 :(得分:3)

最有效的方法是使用Enumerable.Join

var documents = from doc in _list 
                join licenseID in type 
                on doc.LicenseID equals licenseID 
                select doc;

如果要替换列表:

_list = documents.ToList();

你也可以使用Enumerable.Where + List.Contains,但效率不高但更短:

_list = _list.Where(d => type.Contains(d.LicenseID)).ToList();

答案 1 :(得分:0)

这是一个linq查询

var result =  (from cust in _list join id in type on cust.LicenseID equals id select cust).ToArray();

答案 2 :(得分:0)

使用LinQ Where方法,这非常简单:

_list = _list.Where(c => type.Contains(c.LicenseID)).ToList();
相关问题