Вы можете сделать это, используя понимание списка следующим образом:
d['children'] = [v for child in d['children'] for k,v in child.items()]
Используете ли вы C # 3.0 с LINQ? Тогда это довольно просто:
List<string> fields = values.Select(i => i.ToString()).ToList();
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.
If you have LINQ available (in .NET 3.5) and C# 3.0 (for extension methods), then there is quite a nice one liner:
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.
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.
C # 2.0:
List<string> stringList = new List<string>(Array.ConvertAll<object,string>(values, new Converter<object,string>(Convert.ToString)));
Хотя это не один лайнер по отношению к объявлению List <>, дает тот же эффект, не требуя Linq.
List<string> list = new List<string>();
Array.ForEach(values, value => list.Add(value.ToString()));
Array.ConvertAll(inputArray, p => p.ToString())
Преобразует массив типа объект
в массив из строки
. Вы можете преобразовать в массив другого типа, изменив лямбда-выражение.