C# 如何从逗号分隔的字符串创建 List<T>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/910119/
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 create a List<T> from a comma separated string?
提问by Nick Allen
Given the variable
鉴于变量
string ids = Request.QueryString["ids"]; // "1,2,3,4,5";
Is there any way to convert it into a List without doing something like
有什么方法可以将其转换为 List 而无需执行类似操作
List<int> myList = new List<int>();
foreach (string id in ids.Split(','))
{
if (int.TryParse(id))
{
myList.Add(Convert.ToInt32(id));
}
}
采纳答案by Jason
To create the list from scratch, use LINQ:
要从头开始创建列表,请使用 LINQ:
ids.Split(',').Select(i => int.Parse(i)).ToList();
If you already have the list object, omit the ToList() call and use AddRange:
如果您已经拥有列表对象,请省略 ToList() 调用并使用 AddRange:
myList.AddRange(ids.Split(',').Select(i => int.Parse(i)));
If some entries in the string may not be integers, you can use TryParse:
如果字符串中的某些条目可能不是整数,则可以使用 TryParse:
int temp;
var myList = ids.Split(',')
.Select(s => new { P = int.TryParse(s, out temp), I = temp })
.Where(x => x.P)
.Select(x => x.I)
.ToList();
One final (slower) method that avoids temps/TryParse but skips invalid entries is to use Regex:
避免 temps/TryParse 但跳过无效条目的一种最终(较慢)方法是使用 Regex:
var myList = Regex.Matches(ids, "[0-9]+").Cast<Match>().SelectMany(m => m.Groups.Cast<Group>()).Select(g => int.Parse(g.Value));
However, this can throw if one of your entries overflows int (999999999999).
但是,如果您的条目之一溢出 int (999999999999),则可能会抛出此问题。
回答by Konrad Rudolph
Using Linq:
使用 Linq:
myList.AddRange(ids.Split(',').Select(s => int.Parse(s));
Or directly:
或者直接:
var myList = ids.Split(',').Select(s => int.Parse(s));
Also, to prevent the compiler from explicitly generating the (largely redundant) lambda, consider:
此外,为了防止编译器显式生成(主要是冗余的)lambda,请考虑:
var myList = ids.Split(',').Select((Func<string, int>)int.Parse);
(Hint: micro-optimization.)
(提示:微优化。)
There's also TryParse
which should be used instead of Parse
(only) if invalid input is possible and should be handled silently. However, others have posted solutions using TryParse
so I certainly won't. Just bear in mind that you shouldn't duplicate the calculation.
如果无效输入是可能的并且应该静默处理,那么也TryParse
应该使用 which 而不是Parse
(仅)。但是,其他人已经发布了使用的解决方案,TryParse
所以我当然不会。请记住,您不应该重复计算。
回答by Ronald Wildenberg
This should do the trick:
这应该可以解决问题:
myList.Split(',').Select(s => Convert.ToInt32(s)).ToList();
If the list may contain other data besides integers, a TryParse
call should be included. See the accepted answer.
如果列表可能包含除整数之外的其他数据,TryParse
则应包括调用。请参阅已接受的答案。
回答by kastermester
One issue at hand here is how we're gonna deal with values that are not integers (lets assume we'll get some that is not integers). One idea might be to simply use a regex:
这里的一个问题是我们将如何处理非整数值(假设我们会得到一些非整数值)。一种想法可能是简单地使用正则表达式:
^-?[0-9]+$
^-?[0-9]+$
Now, we could combine all this up with (as shown in Konrad's example):
现在,我们可以将所有这些结合起来(如 Konrad 的示例所示):
var myList = ids.Split(',').Where(s => Regex.IsMatch(s, "^-?[0-9]$")).Select(s => Convert.ToInt32(s)).ToList();
That should do the job.
那应该可以完成这项工作。
回答by Dario
Or including TryParse
like in your example:
或者TryParse
在您的示例中包含类似内容:
var res = ids.Split(',').Where(x => { int tmp; return int.TryParse(x, out tmp); }).Select(x => int.Parse(x)).ToList();
回答by Ruben Bartelink
To match the request in terms of performance characteristics and behaviour, it should do the same thing and not go off doign regexes or not doing the 'TryParse':-
为了在性能特征和行为方面匹配请求,它应该做同样的事情,而不是离开 doign regex 或不做“TryParse”:-
ds.Split(',')
.Select( i => {
int value;
bool valid = int.TryParse(out value);
return new {valid, value}
})
.Where(r=>r.valid)
.Select(r=>r.value)
.ToList();
But while correct, that's quite ugly :D
但是虽然正确,但这很丑陋:D
Borrowing from a hint in Jason's comment:-
借用杰森评论中的提示:-
ds.Split(',')
.Select( i => {
int value;
bool valid = int.TryParse(out value);
return valid ? new int?( value) : null;
})
.Where(r=>r != null)
.Select(r=>r.Value)
.ToList();
Or
或者
static class Convert
{
public static Int32? ConvertNullable(this string s)
{
int value;
bool valid = int.TryParse(out value);
return valid ? new int?( value) : null;
}
}
ds.Split(',')
.Select( s => Convert.ConvertNullable(s))
.Where(r=>r != null)
.Select(r=>r.Value)
.ToList();