how to call a function in c# which return type is array
public CD[] GetCDCatalog()
{
XDocument docXML =
XDocument.Load(Server.MapPath("mydata.xml"));
var CDs =
from cd in docXML.Descendants("Table")
select new CD
{
title = cd.Element("title").Value,
star = cd.Element("star").Value,
endTime = cd.Element("endTime").Value,
};
return CDs.ToArray<CD>();
}
I am calling this function on page load ie. string[] arr = GetCDCatalog(); but this is giving Error Cannot implicitly convert 开发者_高级运维type 'Calender.CD[]' to 'string[]' Please suggetst how can i call function on page load which return type is array.
Your method is declared to return a CD[]
, and as the compiler has told you, you can't convert from a CD[]
to a string[]
. Call it like this instead:
CD[] cds = GetCDCatalog();
If you need to convert to a string array then you could use something like this:
string[] cds = GetCDCatalog().Select(x => x.title).ToArray();
Or if you don't really need it in an array, you could just use:
IEnumerable<string> cds = GetCDCatalog().Select(x => x.title);
Change the call in Page.Load to Calender.CD[] arr = GetCDCatalog()
Or use a List:
public List<CD> GetCDCatalog() { XDocument docXML = XDocument.Load(Server.MapPath("mydata.xml"));
var CDs =
from cd in docXML.Descendants("Table")
select new CD
{
title = cd.Element("title").Value,
star = cd.Element("star").Value,
endTime = cd.Element("endTime").Value,
};
return CDs.ToList();
}
The problem is that you are calling it as:
string[] arr = GetCDCatalog();
when GetCDCatalog is returning an array of CD (CD[]).
You need to do:
CD[] arr = GetCDCatalog();
精彩评论