Anirban Ghosh
Anirban Ghosh

Reputation: 125

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'

Cannot implicitly convert type 'System.Linq.IQueryable<LSB.HM.AHME>' to '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:

<LSB.HM.AHME>.Add has some invalid arguements

Upvotes: 0

Views: 121

Answers (3)

Anirban Ghosh
Anirban Ghosh

Reputation: 125

Thanks to all and 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.

Upvotes: 0

Stuart
Stuart

Reputation: 66882

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.

The easiest solution is to use var

        var sList = db.Stnd.Select(s => new AHME
        {
            elementID = s.ID,
            elementName = s.Name,
        }).ToList();

Upvotes: 4

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

You're trying to assign a List<AHME> object to an AHME variable. Try it like this:

        var sList = db.Stnd.Select(s => new AHME
        {
            elementID = s.ID,
            elementName = s.Name,
        }).ToList();

Same for the Join line.

Upvotes: 5

Related Questions