Convert List Of Object To Array
Solution 1:
a field initializer cannot reference the nonstatic field method or property
The issue is that you have a field initializer referencing a non-static field, method or property. The C# compiler won't allow that.
One solution is to move from a field to a property:
Gene[] s { get { return QestionList.ToArray(); } }
The downside of above is that whenever you access s you are effectively cloning QestionList (i.e. it is expensive).
Another would be to leave your field there:
Gene[] s;
and populate it inside your constructor instead:
s = QestionList.ToArray();The upside of doing it in the constructor is that the cloning will occur only once. That is also the downside (if you are altering QestionList then s won't reflect that).
Solution 2:
This should work :). I think that you are using it in wrong place. Please show a code where are you converting list to array.
strings="select * Question, CLO, Question_Type FROM QuestionBank WHERE (Subject = '" + sub + "') AND (chapter = '" + chapter + "') AND (Question_Type = '" + qt.name + "') ORDER BY RAND() LIMIT = '" + qt.numOfType;
SqlCommandcmd=newSqlCommand(s, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
while (dr.Read())
{
stringques= dr["Question"].ToString();
stringquestype= dr["Question_Type"].ToString();
stringquesCLO= dr["CLO"].ToString();
QuestionList.Add(newGene (ques, questype, quesCLO));
}
con.Close();
vargeneArray= QuestionList.ToArray()
}
Solution 3:
Lists can trivially be converted to arrays via ToArray(). The real problem here is simply: timing and location. The code that calls ToArray() is fine in a method, for example it would be fine at the bottom of a method like:
Gene[] GetThings(string subject, string chapter, ...)
{
var list = new List<Gene>();
... some code that populates list
return list.ToArray();
}
Likewise, at the end of that method you could assign to a property or field:
SomeMember = list.ToArray();
Post a Comment for "Convert List Of Object To Array"