C# 方法返回类型 list<string> 还是泛型方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10937339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method return type list<string> or generic method?
提问by Mitja Bonca
I would like that the method has a specfic return type, but somehow I cannot make it work.
我希望该方法具有特定的返回类型,但不知何故我无法使其工作。
I have an XML structure:
我有一个 XML 结构:
<Notifications>
<Alerts>
<Max>3<Max/>
<Med>2<Med/>
<Min>1<Min/>
</Alerts>
</Notifications>
I would like to get out the values of Max, Med, Min. But the main point is I DO NOT want any foreach loops at all, I only want that the method has a List<string> return type, or even better to make a generic return type.
我想找出Max, Med,的值Min。但重点是我根本不需要任何 foreach 循环,我只希望该方法具有 List<string> 返回类型,或者甚至更好地创建通用返回类型。
The point is, I don't have any custom class (and I don't want to have it) that I would fill its properties.
关键是,我没有可以填充其属性的任何自定义类(并且我不想拥有它)。
This is what I have some far, but I got an error on the "List()" annonymus method:
这就是我所拥有的,但我在“List()”匿名方法上遇到了错误:
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
}
----------
----------
And how would it look that this method about would be a generic return type? This is NOT OK:
这个方法看起来如何是一个通用的返回类型?这不正常:
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();
}
The error message is:
错误信息是:
Cannot convert type 'System.Collections.Generic.List' to 'T'
无法将类型“System.Collections.Generic.List”转换为“T”
采纳答案by Douglas
You cannot transfer anonymous types across method boundaries (in your case, as the generic type of the List<T>that is being returned from your method).
您不能跨方法边界传输匿名类型(在您的情况下,作为List<T>从您的方法返回的泛型类型)。
You should define a class or struct with Max, Med, and Minas properties, and initialize a list of its instances from your method.
您应该使用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();
}
Edit: As an alternative, you couldreturn a list of dictionaries mapping the property names to their values:
编辑:作为替代方案,您可以返回将属性名称映射到其值的字典列表:
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();
}
You could them access your values using code like:
您可以使用以下代码访问您的值:
string firstMin = alerts[0]["Min"];
回答by ΩmegaMan
Try this instead:
试试这个:
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>";
回答by Jon Senchyna
Unfortunately, I don't know how to get MAX, MED, and MIN returned in separate entries in a List within the LINQ query. What you can do though, is have your LINQ query put MIN, MED, and MAX into a List object, and then return the first row.
不幸的是,我不知道如何在 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. - Your end tags for MIN, MAX, and MED are formatted incorrectly, the '/' should be before the name, not after.
PS - 您的 MIN、MAX 和 MED 结束标签格式不正确,“/”应该在名称之前,而不是之后。

