我想将a转换List<string>为a List<int>.
这是我的代码:
void Convert(List<string> stringList)
{
List<int> intList = new List<int>();
for (int i = 0; i < stringList.Count; i++)
{
intList.Add(int.Parse(stringList[i]));
}
)
Run Code Online (Sandbox Code Playgroud)
Pet*_*den 27
您可以使用而不是使用LINQ List<T>.ConvertAll<TOutput>(...)
List<int> intList = stringList.ConvertAll(int.Parse);
Run Code Online (Sandbox Code Playgroud)
Mar*_*rco 13
我建议使用TryParse(),以防某些值无法转换为int.为此,我创建了一个扩展方法.下面是我的演示LinqPad代码.
void Main()
{
List<string> sourceList = new List<string> {"1", "2","3", "qwert","4", "5","6", "7","asdf", "9","100", "22"};
//Dump is a LinqPad only method. Please ignore
sourceList.ConvertToInt().Dump();
}
static public class HelperMethods
{
static public List<int> ConvertToInt(this List<string> stringList)
{
int x = 0;
var intList = stringList.Where(str => int.TryParse(str, out x))
.Select (str => x)
.ToList();
return intList;
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,只解析数字int值,并优雅地忽略其余值.如果您愿意,可以内置一些错误处理/通知.
/编辑 基于Peter Kiss的建议这里是一个基于IEnumerable接口的更通用的方法.
static public IEnumerable<int> ConvertToInt(this IEnumerable<string> source)
{
int x = 0;
var result = source.Where(str => int.TryParse(str, out x))
.Select (str => x);
return result;
}
Run Code Online (Sandbox Code Playgroud)
有了这个,你只需要在调用AsEnumerable()之前调用ConvertToInt()结果当然是类型的IEnumerable<Int32>,从这里开始,你可以通过使用.ToList()或数组或者你需要的任何东西轻松地将它转换为List .
与Linq:
var intList = stringList.Select(x => int.Parse(x)).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35408 次 |
| 最近记录: |