[英]Creating a property with the object of the same class in c#
What I am trying is the following: 我正在尝试以下内容:
public class AHME
{
public string elementName { get; set; }
public long? elementID { get; set; }
public AHME[] children { get; set; }
public static AHME[] GetAHME()
{
var listS = new List<AHME>();
using (var db = new DBEntities())
{
AHME sList = db.Stnd.Select(s => new AHME
{
elementID = s.ID,
elementName = s.Name,
}).ToList();
listS.Add(sList);
var listT = new List<AHME>();
using (var db = new DBEntities())
{
AHME tList = db.Tr.Join(db.Us, t => t.ID, u => u.ID, (t, u) => new AHME
{
elementID = t.ID,
elementName = u.FirstNames + " " + u.LastName,
children=listS.ToArray(),
});
listT.Add(tList).ToList();
}
return listT.ToArray();
}
}
}
But I am getting errors like: 但是我收到如下错误:
Cannot implicitly convert type '
System.Collections.Generic.List<LSB.HM.AHME>
' to 'LSB.HM.AHME
'无法将类型'
System.Collections.Generic.List<LSB.HM.AHME>
'隐式转换为'LSB.HM.AHME
'Cannot implicitly convert type '
System.Linq.IQueryable<LSB.HM.AHME>
' to 'LSB.HM.AHME
'.无法将类型'
System.Linq.IQueryable<LSB.HM.AHME>
'隐式转换为'LSB.HM.AHME
'。 An explicit conversion exists (are you missing a cast?)存在显式转换(您是否缺少演员表?)
Additionally, for " AHME sList
" if I could use var type like var sList
, then its throwing error that: 另外,对于“
AHME sList
”,如果我可以使用var sList
类的var sList
,则其抛出错误是:
<LSB.HM.AHME>.Add
has some invalid arguements<LSB.HM.AHME>.Add
有一些无效的论点
You're trying to assign a List<AHME>
object to an AHME
variable. 您正在尝试将
List<AHME>
对象分配给AHME
变量。 Try it like this: 像这样尝试:
var sList = db.Stnd.Select(s => new AHME
{
elementID = s.ID,
elementName = s.Name,
}).ToList();
Same for the Join
line. Join
行也一样。
The problems lie in the blocks like: 问题出在以下块中:
AHME sList = db.Stnd.Select(s => new AHME
{
elementID = s.ID,
elementName = s.Name,
}).ToList();
You cannot cast an IList<T>
to a T
. 您不能将
IList<T>
转换为T
The easiest solution is to use var
最简单的解决方案是使用
var
var sList = db.Stnd.Select(s => new AHME
{
elementID = s.ID,
elementName = s.Name,
}).ToList();
Thanks to all and Writwick. 感谢所有人和Writwick。
I have used a foreach loop to iterate over the var sList and add the items in the sList in the ListS and conceptually I think it should be like that, as sList contains list of objects and those require to be added one by one to the ListS. 我使用了一个foreach循环来遍历var sList并在ListS的sList中添加项目,从概念上讲,我认为应该是这样,因为sList包含对象列表,并且需要逐一添加到ListS 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.