简体   繁体   中英

Linq Join in c#

friend i'm working in Linq. I use join in linq query with Entity Model as below.

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 };

i want to convert the Record var in List of object, so i create a intermediate object which hold both entites values(product,category). Now when i cast this var to list like

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

as Record.ToList(); is compiler error. how i cast the var object to list in order to bind it with listview in frontend. Is there any alternative in lambda which will be also appreciated. Is my approach is right?

my test class is as:

class test{
string catname;
string productname;
}

use ToList() on your query.

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();

In order to make it work you need to define your test class as follows (you need to define properties)

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

Create new Test and set the properties accordingly and finally call 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();

If have class like below

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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