我已经检索到我的特定类(class)的列表,其中包含 150 条记录。 现在,我只想要那些在我的另一个 int 列表中具有 Licenseid 的记录。
例如我的主列表
List<CustomerDocument> _list = GetListByID(CustomerID);
在此列表中,我有 LicenseID、CustomerID、CustomerName、Type、Age 等列
和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 类。
现在假设,如果 Int 列表有三个记录,那么我想要使用 Linq 在我的 Int 列表中具有这三个 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
}
最佳答案
最有效的方法是使用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();
关于c# - 使用 Linq 从列表中过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554405/