繁体   English   中英

Linq加入C#

[英]Linq Join in c#

朋友,我在Linq工作。 我在linq查询中使用Join与实体模型,如下所示。

var Records = from Cats in Context.Categories
join prod in Context.Products on Cats.Id equals prod.Category_Id
select new { CatName = Cats.Name, ProdName = prod.Name };

我想在对象列表中转换Record var,所以我创建了一个同时包含两个实体值(product,category)的中间对象。 现在当我将这个变量转换为类似

List<test> testList = (List<test>)Records;

作为Record.ToList(); 是编译器错误。 我如何将var对象转换为列表,以便将其与前端中的listview绑定。 在lambda中是否有其他选择也将不胜感激。 我的方法正确吗?

我的测试课是:

class test{
string catname;
string productname;
}

在查询中使用ToList()

var Records = (from Cats in Context.Categories
               join prod in Context.Products on Cats.Id equals prod.Category_Id
               select new test { CatName = Cats.Name, ProdName = prod.Name }).ToList();

为了使其正常工作,您需要按以下方式定义测试类(您需要定义属性)

public class test {
   public string catname {get;set;}
   public string productname {get;set;}
}

创建new Test并相应地设置属性,最后调用ToList

List<test> testList = (from c in Context.Categories
join p in Context.Products on c.Id equals p.Category_Id
select new Test{ Category= c, Product= p}).ToList();

如果有如下课

public class Test{

    public string CatName{ get; set; }
    public string ProductnName{ get; set; }

}

List<test> testList = (from c in Context.Categories
join p in Context.Products on c.Id equals p.Category_Id
select new Test{ CatName= c.Name, ProductnName= p.Name}).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM