如何从c#中的方法返回一个列表
本文关键字:列表 一个 返回 方法 | 更新日期: 2023-09-27 18:04:36
如何将包含LINQ结果的列表返回给SQLquery?我正在尝试这个实现,但是我得到了这个错误。
不能隐式转换类型
'System.Collections.Generic.List<AnonymousType#1>'
来'System.Collections.Generic.List<object>
如有任何帮助,不胜感激。
public List<Object> getShoes()
{
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
select new { s.ShoeID, s.Size, s.PrimaryColor, s.SecondaryColor, s.Quantity, m.ModelName, m.Price, b.BrandName, i.ImagePath };
return query.ToList();
}
匿名类型是专门设计为完全在定义它们的范围内使用的。如果希望从该方法返回查询的结果,则应该创建一个新的命名类型来表示查询的结果,并选择该命名类型的实例,而不是匿名类型的实例。
如果T是匿名类型,则不能返回List;您需要返回一个已知类型。您可以创建一个类
public class MyResult
{
public string ShoeID {get; set;}
public string Size {get; set;}
public string PrimaryColor {get; set;}
public string SecondaryColor {get; set;}
public string Quantity {get; set;}
public string ModelName {get; set;}
public string Price {get; set;}
public string BrandName {get; set;}
public string ImagePath {get; set;}
}
然后改变你的选择,像这样
select new MyResult { ShoeID = s.ShoeID, Size = s.Size, PrimaryColor = s.PrimaryColor ........ };
和你的方法签名将更改为
public List<MyResult> getShoes()