c# - 使用 Linq 从列表中过滤列表

标签 c# asp.net linq list

我已经检索到我的特定类(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 类。

This is my debug at solution

现在假设,如果 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
  }

enter image description here

最佳答案

最有效的方法是使用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/

相关文章:

c# - EF 代码优先 - 获取 DynamicProxies 而不是对象。为什么?

c# - 如何向查找字段添加值?

asp.net - 如何在 asp.net 网页中实现 html 表单 - asp.net 中的两种表单问题

c# - ASP.NET 是否具有获取用户历史记录的内置功能?

c# - 使用 linq,我如何从另一个 IEnumerable<> 的属性创建一个 IEnumerable<>

linq - FluentValidation for WP7 - 验证简单类型​​(字符串)

c# - 如何在 aspx 内容占位符内的 html 表单元素上设置特定 id

c# - 在添加自己的 LinearLayout 期间无法激活 JNI 句柄 - Xamarin Android

c# - DB ConnectionState = Open 但 context.SaveChanges 抛出 "connection broken"异常

c# - 从 Amazon SQS 检索消息属性名称