且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在linq中选择新的

更新时间:2023-12-04 13:06:34

只要您在本地范围内,匿名对象就可以工作。现在,一旦将它存储在会话中并将其取回,编译器需要知道检索到的对象的类型。所以你可以创建一些DTO类型的东西来完成这个任务,比如

  public class DTOCompany 
{
public int id {get; set;}
public string name {get; set;}
}

你可以在你的linq查询中使用这个对象,比如

  var CountryCompanyDB = from b in dc.PropertyCompanies where (b.Country.Contains(txtSearch))选择新的DTOCompany {id = b.id,name = b.name}; 

从会话中取回时,您可以将其转换为DTOCompany列表,如

  var result =(List< DTOCompany>)Session [CountryCompany]; 


var CountryCompanyDB = from b in dc.PropertyCompanies where (b.Country.Contains(txtSearch)) select;

Session["CountryCompany"] = CountryCompanyDB.ToList();

if(test==1)
{
    var result = (List<PropertyCompany >)Session["CountryCompany"];
}

this worked fine

but i want

var CountryCompanyDB = from b in dc.PropertyCompanies where (b.Country.Contains(txtSearch)) select new {b.id , b.name};

Session["CountryCompany"] = CountryCompanyDB.ToList();

if(test==1)
{
    var result = (List<PropertyCompany new {b.id , b.name}>)Session["CountryCompany"];//does not can this work
}

i want select new of Session["CountryCompany"] how can perform this work.

Edit

class   kbc {
    public Int64 id { get; set; }
    public string  name { get; set; }
}


  var CountryCompanyDB = from b in dc.PropertyCompanies where (b.Country.Contains(txtSearch)) select new { id=b.IdCompany ,name=b.NameCompany} ;

 if(test==1)
{
    var result = (List<kbc>)Session["CountryCompany"];
}

sayError:
Unable to cast object of type 'System.Collections.Generic.List1[<>f__AnonymousType02[System.Int64,System.String]]' to type 'System.Collections.Generic.List`1[FullSearch+kbc]

Anonymous objects work as long as you are in local scope. Now once you have stored it in session and retrieved it back compiler needs to know the type of retrieved object. so you can create some DTO type of thing to accomplish this task like

public class DTOCompany
{
  public int id{get;set;}
  public string name{get;set;}
}

you can use this object in you linq query like

var CountryCompanyDB = from b in dc.PropertyCompanies where (b.Country.Contains(txtSearch)) select new DTOCompany{id=b.id ,name = b.name};

when retrieving it back from session you can cast it as list of DTOCompany like

var result = (List<DTOCompany>)Session["CountryCompany"];