我正在使用 ASP.net Web Service C#.net3.5 并使用 LINQ TO SQL 来操作 SQL 数据库
我想从Countries
表中返回所有国家信息,所以我编写了一个返回对象列表的 web 方法,每个对象有两个数据字段Country_Id
,Country_Name
方法如下:
public List<CountryObject> ReturnAllCountries()
{
ProjectTwoDataBaseDataContext DataBase = new ProjectTwoDataBaseDataContext();
var Country = from a in DataBase.Countries
select new {a.Country_Id,a.Country_Name };
CountryObject TempObject = new CountryObject();
List<CountryObject> TempList = new List<CountryObject>();
foreach (var a in Country)
{
TempObject.setCountry_Id(a.Country_Id);
TempObject.setCountry_Name(a.Country_Name);
TempList.Add(TempObject);
}
return TempList;
}
但是当我运行代码时,我得到一个包含相同对象的列表,并且该对象具有从上一轮 Foreach 获得的值。
我尝试以下:
public List<CountryObject> ReturnAllCountries()
{
ProjectTwoDataBaseDataContext DataBase = new ProjectTwoDataBaseDataContext();
var Country = from a in DataBase.Countries
select new {a.Country_Id,a.Country_Name };
CountryObject TempObject;
List<CountryObject> TempList = new List<CountryObject>();
foreach (var a in Country)
{
TempObject = new CountryObject();
TempObject.setCountry_Id(a.Country_Id);
TempObject.setCountry_Name(a.Country_Name);
TempList.Add(TempObject);
}
return TempList;
}
我得到了我想要的>>为什么????