我希望该方法具有特定的返回类型,但不知怎的,我无法使其工作。
我有一个XML结构:
<Notifications>
<Alerts>
<Max>3<Max/>
<Med>2<Med/>
<Min>1<Min/>
</Alerts>
</Notifications>
我想了解Max
,Med
,Min
的值。但重点是我根本不需要任何foreach循环,我只希望该方法有一个List&lt; string&gt;返回类型,甚至更好地制作通用返回类型。
重点是,我没有任何自定义类(我不想拥有它),我会填充它的属性。
这是我有点远,但我在“List()”annonymus方法上出错:
Here it returns:
List<string> items = GetAlerts();
//method to read:
public List<string> GetAlerts()
{
return xmlDoc1.Descendants("Notifications").Elements("Alerts").Select(s => new
{
MAX = s.Element("Max").Value,
MED = s.Element("Med").Value,
MIN = s.Element("Min").Value
}).ToList(); //error on this line
}
看起来这个方法看起来是一般的返回类型怎么样?这不行:
Here it returns:
List<object> items = setBLL2.GetAlert<List<object>>();
public T GetAlert<T>() where T:class
{
return (T)xmlDoc1.Descendants("Notifications").Elements("Alerts").Select(s => new
//ERROR up here before (T
{
MAX = s.Element("Max").Value,
MED = s.Element("Med").Value,
MIN = s.Element("Min").Value
}).ToList();
}
错误消息是:
无法将类型'System.Collections.Generic.List'转换为'T'
答案 0 :(得分:4)
您不能跨方法边界传输匿名类型(在您的情况下,作为从您的方法返回的List<T>
的泛型类型)。
您应该定义一个以Max
,Med
和Min
作为属性的类或结构,并从您的方法初始化其实例列表。
public class Alert
{
public string Max { get; set; }
public string Med { get; set; }
public string Min { get; set; }
}
public IList<Alert> GetAlerts()
{
return (xmlDoc1.Descendant("Notifications").Elements("Alerts").Select(s =>
new Alert
{
Max = s.Element("Max").Value,
Med = s.Element("Med").Value,
Min = s.Element("Min").Value
}).ToList();
}
修改:作为替代方案,可以返回将属性名称映射到其值的字典列表:
public IList<Dictionary<string,string>> GetAlerts()
{
return (xmlDoc1.Descendant("Notifications").Elements("Alerts").Select(s =>
new Dictionary<string,string>
{
{ "Max", s.Element("Max").Value },
{ "Med", s.Element("Med").Value },
{ "Min", s.Element("Min").Value }
}).ToList();
}
您可以使用以下代码访问您的值:
string firstMin = alerts[0]["Min"];
答案 1 :(得分:0)
请改为尝试:
void Main()
{
List<string> alerts =
XDocument.Parse(Data)
.Descendants("Alerts")
.Elements()
.Select (nd => nd.Value)
.ToList();
alerts.ForEach(al => Console.WriteLine ( al ) ); // 3 2 1 on seperate lines
}
// Define other methods and classes here
const string Data = @"<?xml version=""1.0""?>
<Notifications>
<Alerts>
<Max>3</Max>
<Med>2</Med>
<Min>1</Min>
</Alerts>
</Notifications>";
答案 2 :(得分:0)
不幸的是,我不知道如何在LINQ查询中的List中的单独条目中返回MAX,MED和MIN。你可以做的是让你的LINQ查询将MIN,MED和MAX放入List对象,然后返回第一行。
public IList<Alert> GetAlerts()
{
var xmlDoc1 = XDocument.Parse(XML, LoadOptions.None);
var entries = xmlDoc1.Descendants("Notifications").Elements("Alerts").Select(s => new
List<string> {
s.Element("Max").Value,
s.Element("Med").Value,
s.Element("Min").Value
}).ToList();
// Make sure we don't get an ArgumentOutOfRangeException
if (entries.Count > 0)
{
return entries[0];
}
else
{
return new List<string>();
}
}
P.S。 - MIN,MAX和MED的结束标记格式不正确,'/'应位于名称之前,而不是之后。