在linq中选择new

本文关键字:new 选择 linq | 更新日期: 2023-09-27 18:02:48

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

这很好

但我想要

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
}

我想选择新的会话["CountryCompany"]如何执行这项工作。

编辑

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:
无法将类型为"System.Collections.Generic.List 1[<>f__AnonymousType0 2[System.Int64,System.String]]"的对象强制转换为类型"System.Collections.Generic.List`1[FullSearch+kbc]

在linq中选择new

在LINQ语句中定义PropertyCompany

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

其中IDName可能是PropertyCompany类的属性名。

只要您在本地范围内,匿名对象就可以工作。现在,一旦您将它存储在会话中并检索回来,编译器就需要知道检索到的对象的类型。所以你可以创建一些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)) select new DTOCompany{id=b.id ,name = b.name};

当从会话中检索它时,您可以将其转换为类似的DTOCompany列表

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

匿名类型只能用作更复杂算法的中间类型。若要将结果保存到变量中或传递到方法中,则应该创建特定的类。

new {b.id , b.name}是一个匿名类型,因此不能方便地引用它。您应该使用代码中定义的正则类,或者使用Tuple<int,string>(即select Tuple.Create(b.id, b.name)(-然后:

var result = (List<Tuple<int,string>>)Session["CountryCompany"];

Session["CountryCompany"]不会持有List<PropertyCompany>,但它将是一个普通的列表,我认为它与<string,string>类似。执行ToList()部分时,请检查类型。

使用匿名类型可以做什么。。是在select中使用它们,然后在foreach中使用它。

var q = _someCollection.Where(c => c.Id == 100).Select (new { Id = c.Id, Name = c.Name});
foreach(var p in q) {
   var id = p.Id;
}

这会起作用,因为实际上,编译器知道新{Age=c.Age,Position=c.Pos}的类型(它会为此生成额外的信息(。

一旦您转换到List,那么您已经转换到对象(放入Session(,您就无法再获得类型信息。

我将介绍一些真实类型CountryInfo和更改后的查询;

var q = _someCollection.Where(c => c.Id == 100).Select(new ContryInfo { Id = c.Id, Name = c.Name}).
Session["a"] = q.ToList();
var list = (IList<ContryInfo>)Session["a"];