我正在尝试将列表转换为以下对象:
public static List<Object> lstproductname = new List<Object>();
var partialResult = db.Company.OrderBy(x => x.id).Take(1);
var finalResult = (from j in db.productListDbSet
join comp in partialResult
on j.mstr_company_id equals comp.id
select new { j.id, j.name }).OrderBy(x => x.name).ToList();
lstproductname = finalResult.Cast<object>().ToList();
尝试使用foreach作为结果,但没有运气..
foreach (var d in lstproductname.ToList())
{
string s = d.ToString();
}
lstproductname
的内容类似于{ id = 1, name = "Product1" }
我需要获取id value
和name value
,但遗憾的是无法获得它。
我试过像foreach那样的东西,比如
foreach (var d in lstproductname.ToList())
{
string id = d.id.ToString();
string name = d.name.ToString();
}
这个不起作用..
string id = d.id.ToString();
string name = d.name.ToString();
任何想法如何获得这一点都是高度赞赏的。
答案 0 :(得分:1)
请勿使用object
。投入一个具体的类或什么的。声明:
class ResultItem
{
public int Id { get; set; }
public string Name { get; set; }
}
然后这样做:
var finalResults = (from j in db.productListDbSet
join comp in partialResult
on j.mstr_company_id equals comp.id
select new ResultItem{ Id=j.id, Name=j.name })
.OrderBy(x => x.name).ToList();
foreach (var result in finalResults)
{
string id = result.Id.ToString();
string name = result.Name.ToString();
//do stuff...
}
答案 1 :(得分:0)
这是解决方案:
创建一个新类
public class FinalProduct
{
public int id { get; set; }
public string name { get; set; }
}
<强> LINQ 强>
public static List<FinalProduct> lstproductname = new
List<FinalProduct>();
var partialResult = db.Company.OrderBy(x => x.id).Take(1);
var finalResult = (from j in db.productListDbSet
join comp in partialResult
on j.mstr_company_id equals comp.id
select new FinalProduct {id= j.id,name= j.name }).OrderBy(x => x.name).ToList();
lstproductname = finalResult.Cast<FinalProduct>().ToList();
foreach (var d in lstproductname.ToList())
{
String id = d.id.ToString();
String name = d.name.ToString();
}
来自@Stephen Muecke
的解决方案想法谢谢..