我有一张名为Company的表 在这个我试图使用linq查询访问该表的数据并转换为公司Calss像
List<Company> companyData = (from c in dataContext.Companies
select new
{
CompanyName =c.CompanyName,
Address1 =c.Address1,
Addredd2 =c.Address2,
city=c.City.CityName,
state =c.State.StateName,
country =c.Country.CountryName,
Telephone1 =c.Telephone1,
Telephone2 =c.Telephone2,
Mobile1 =c.Mobile1,
Mobile2=c.Mobile2,
Email1 =c.Email1,
Email2 = c.Mobile2,
Fax1=c.Fax1,
Fax2=c.Fax2,
TinNo=c.TinNo,
IsGroupCompany=c.IsGroupCompany
}).ToList<Company>();
但它给出了像ToList()这样的错误有一些无效的参数 如何在列名中获取列表格式的数据
Thaks in Advance
答案 0 :(得分:3)
我认为你正在寻找这个:
List<Company> companyData = (from c in dataContext.Companies select new Company {
CompanyName = c.CompanyName,
Address1 = c.Address1,
Address2 = c.Address2,
City = c.City,
State = c.State,
Country = c.Country,
Telephone1 = c.Telephone1,
Telephone2 = c.Telephone2,
Mobile1 = c.Mobile1,
Mobile2 = c.Mobile2,
Email1 = c.Email1,
Email2 = c.Email2,
Fax1 = c.Fax1,
Fax2 = c.Fax2,
TinNo = c.TinNo,
IsGroupCompany = c.IsGroupCompany }
).ToList();
换句话说,您的代码正在实例化anonymous type,但您正在尝试创建Company对象列表。因此,请改为实例化Company对象。
但是,您可能无需创建一组新的公司对象,并且从另一组公司对象中复制其属性。如果这是真的,你可以这样做:
List<Company> companyData = dataContext.Companies.ToList();
如果您需要以不同方式命名属性,那么使用匿名类型是正确的。在这种情况下,您必须使用var
关键字,因为对象不再是Company
类的实例:
var companyData = (from c in dataContext.Companies
select new
{
CompanyName =c.CompanyName,
Address1 =c.Address1,
Addredd2 =c.Address2,
city=c.City.CityName,
state =c.State.StateName,
country =c.Country.CountryName,
Telephone1 =c.Telephone1,
Telephone2 =c.Telephone2,
Mobile1 =c.Mobile1,
Mobile2=c.Mobile2,
Email1 =c.Email1,
Email2 = c.Mobile2,
Fax1=c.Fax1,
Fax2=c.Fax2,
TinNo=c.TinNo,
IsGroupCompany=c.IsGroupCompany
}).ToList();
答案 1 :(得分:1)
List<Company> companyData = (from c in dataContext.Companies
select new Company() { ... }).ToList();
答案 2 :(得分:1)
如果你的意思是DataTable,那么你可以这样做:
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("name", typeof(string));
table.Columns.Add("address", typeof(string));
table.Rows.Add("name 1", "address 1");
table.Rows.Add("name 1", "address 1");
var query = table.AsEnumerable().Select(s => new Company { Name = (string)s["name"], Address = (string)s["address"] }).ToList();
}
}
class Company
{
public string Name { get; set; }
public string Address { get; set; }
}
答案 3 :(得分:0)
try this :-
List<Company> companyData = (from c in dataContext.Companies
select new Company
{
CompanyName =c.CompanyName,
Address1 =c.Address1,
Addredd2 =c.Address2,
city=c.City.CityName,
state =c.State.StateName,
country =c.Country.CountryName,
Telephone1 =c.Telephone1,
Telephone2 =c.Telephone2,
Mobile1 =c.Mobile1,
Mobile2=c.Mobile2,
Email1 =c.Email1,
Email2 = c.Mobile2,
Fax1=c.Fax1,
Fax2=c.Fax2,
TinNo=c.TinNo,
IsGroupCompany=c.IsGroupCompany
}).ToList();