Skip to main content
 首页 » 编程设计

c#之在两个选定列表中拆分 linq 连接查询并使用 Tuple 返回两个列表

2024年02月06日14over140

具有以下代码:实体 linq 查询结果选择两个表。 查询中所有数据可用,但无法将结果拆分为两个列表。

 public Tuple<List<sale>, List<product>>  SearchProduct(int productId = -1, string searchProduct = "") 
    { 
        //ToDo: searchProduct not working...gives nothing 
        var companyId = DalSession.DalGetCurrentUser().Company_ID; 
        using (var entity = new secondsoftEntities()) 
        { 
            var query = (from s in entity.sales 
                         join p in entity.products on s.Product_ID equals p.ProductID 
                         where productId > 0 ? s.Product_ID == productId : s.Company_ID == companyId 
                         select new { s, p }).ToList(); 
            if (!string.IsNullOrEmpty(searchProduct)) 
              { 
                query = query.FindAll(x => x.p.Description.ToLower().Contains(searchProduct.ToLower())); 
             }  
 
 
 
            // split s as List<sale> and p as List<product> to tuple output 
 
 
            return Tuple.Create(new List<sale>(), new List<product>() ); 
        } 
    } 

在查询结果中,我看到了 s 和 p,但是如何将它们精确地作为一个列表,其中包含属性,以便我可以在元组中返回它们。

谢谢迪南

请您参考如下方法:

return Tuple.Create(query.Select(x => x.s).ToList(), 
                    query.Select(x => x.p).ToList());