如何在一行 C# 3.0 中将 object[] 转换为 List<string>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/868572/
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
How to convert object[] to List<string> in one line of C# 3.0?
提问by Edward Tanguay
ok I give up, how do you do this in one line?
好吧,我放弃了,你如何在一行中做到这一点?
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//List<string> fields = values.ToList<string>();
//List<string> fields = values as List<string>;
//List<string> fields = (List<string>)values;
List<string> fields = new List<string>();
foreach (object value in values)
{
fields.Add(value.ToString());
}
//process the fields here knowning they are strings
...
}
采纳答案by Matt Hamilton
Are you using C# 3.0 with LINQ? It's pretty easy then:
您在 LINQ 中使用 C# 3.0 吗?那么这很容易:
List<string> fields = values.Select(i => i.ToString()).ToList();
回答by Noldorin
If you have LINQ available (in .NET 3.5) and C# 3.0 (for extension methods), then there is quite a nice one liner:
如果您有可用的 LINQ(在 .NET 3.5 中)和 C# 3.0(用于扩展方法),那么有一个很好的单行代码:
var list = values.Cast<string>().ToList();
You're not going get anything much shorter that what you've posted for .NET 2.0/C# 2.0.
您不会得到比您为 .NET 2.0/C# 2.0 发布的内容更短的内容。
Caveat:I just realised that your object[]
isn't necessarily of type string
. If that is in fact the case, go with Matt Hamilton's method, which does the job well. If the element of your array are in fact of type string
, then my method will of course work.
警告:我刚刚意识到您object[]
的不一定是 type string
。如果情况确实如此,请使用马特·汉密尔顿的方法,它可以很好地完成工作。如果您的数组元素实际上是 type string
,那么我的方法当然会起作用。
回答by Pat
While not a one liner with respect to List<> declaration, gives you same effect without requiring Linq.
虽然不是关于 List<> 声明的单行代码,但无需 Linq 即可提供相同的效果。
List<string> list = new List<string>();
Array.ForEach(values, value => list.Add(value.ToString()));
回答by Daniel Earwicker
One more variant that might be correct:
另一种可能正确的变体:
List<string> list = values.OfType<string>().ToList();
This will filter out any objects in the original list that are not string
objects, instead of either throwing an exception or trying to convert them all into strings.
这将过滤掉原始列表中不是string
对象的任何对象,而不是抛出异常或尝试将它们全部转换为字符串。
回答by Chris Persichetti
C# 2.0:
C# 2.0:
List<string> stringList = new List<string>(Array.ConvertAll<object,string>(values, new Converter<object,string>(Convert.ToString)));
回答by Suresh Deevi
Array.ConvertAll(inputArray, p => p.ToString())
This converts an array of object
type to array of string
. You can convert to other type array by changing the lambda expression.
这将object
类型数组转换为数组string
。您可以通过更改 lambda 表达式来转换为其他类型的数组。