题
假设我有一个网页,当前通过 url 参数接受单个 ID 值:
http://example.com/mypage.aspx?ID=1234
我想改变它以接受 列表 id,像这样:
http://example.com/mypage.aspx?IDs=1234,4321,6789
所以我的代码可以通过以下方式将其作为字符串使用 context.Request.QueryString[“ID”]。 将该字符串值转换为 List<int> 的最佳方法是什么?
编辑: 我知道如何在逗号上执行 .split() 来获取字符串列表,但我问是因为我不知道如何轻松地将字符串列表转换为 int 列表。这仍然在 .Net 2.0 中,所以没有 lambda。
解决方案
无意冒犯那些提供明确答案的人,但很多人似乎是在回答你的问题,而不是解决你的问题。您想要多个 ID,因此您认为可以这样:
http://example.com/mypage.aspx?IDs=1234,4321,6789
问题是这是一个不稳健的解决方案。以后如果想要多个值,如果有逗号怎么办?更好的解决方案(这在查询字符串中完全有效)是使用具有相同名称的多个参数:
http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789
然后,无论您使用什么查询字符串解析器都应该能够返回 ID 列表。如果它不能处理这个(并且还处理分号而不是&符号),那么它就坏了。
其他提示
像这样的事情可能会起作用:
public static IList<int> GetIdListFromString(string idList)
{
string[] values = idList.Split(',');
List<int> ids = new List<int>(values.Length);
foreach (string s in values)
{
int i;
if (int.TryParse(s, out i))
{
ids.Add(i);
}
}
return ids;
}
然后将使用:
string intString = "1234,4321,6789";
IList<int> list = GetIdListFromString(intString);
foreach (int i in list)
{
Console.WriteLine(i);
}
您可以从数组实例化 List<T>。
VB.NET:
Dim lstIDs as new List(of Integer)(ids.split(','))
尽管如果数组包含非 int 元素,这很容易出现转换错误
我能想到的就是循环遍历字符串列表(您通过执行拆分获得的)并执行类似的操作 int.TryParse()
一个接一个地对它们进行处理,并将它们放入一个新的 List<int>
. 。将它封装在一个很好的小帮助方法中,这样就不会太可怕了。
如果你喜欢实用的风格,你可以尝试这样的
string ids = "1,2,3,4,5";
List<int> l = new List<int>(Array.ConvertAll(
ids.Split(','), new Converter<string, int>(int.Parse)));
没有 lambda,但您确实有转换器和谓词以及可以通过方法制作的其他好东西。
我懂了 我的答案 来得相当晚,即其他几个人也写过同样的内容。因此,我提出了一种使用正则表达式来验证和划分字符串的替代方法。
class Program
{
//Accepts one or more groups of one or more digits, separated by commas.
private static readonly Regex CSStringPattern = new Regex(@"^(\d+,?)*\d+$");
//A single ID inside the string. Must only be used after validation
private static readonly Regex SingleIdPattern = new Regex(@"\d+");
static void Main(string[] args)
{
string queryString = "1234,4321,6789";
int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
}
private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
{
if (!CSStringPattern.IsMatch(csString))
throw new FormatException(string.Format("Invalid comma separated string '{0}'",
csString));
List<int> ids = new List<int>();
foreach (Match match in SingleIdPattern.Matches(csString))
{
ids.Add(int.Parse(match.Value)); //No need to TryParse since string has been validated
}
return ids.ToArray();
}
}
最终的代码片段是我希望从所有建议中得到最好的:
Function GetIDs(ByVal IDList As String) As List(Of Integer)
Dim SplitIDs() As String = IDList.Split(new Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
GetIDs = new List(Of Integer)(SplitIDs.Length)
Dim CurID As Integer
For Each id As String In SplitIDs
If Integer.TryParse(id, CurID) Then GetIDs.Add(CurID)
Next id
End Function
我希望能够通过一两行内联代码来完成它。一行创建字符串数组,并希望在框架中找到一些我还不知道的东西来处理将其导入到可以智能处理转换的 List<int> 中。但如果我必须将其转移到一种方法中,那么我会的。是的,我正在使用 VB。我只是更喜欢用 C# 来提问,因为它们会吸引更多的受众,而且我也同样流利。
split 是我首先想到的,但它返回一个数组,而不是一个 List;你可以尝试这样的事情:
List<int> intList = new List<int>;
foreach (string tempString in ids.split(',')
{
intList.add (convert.int32(tempString));
}
从 URL 中提取值后,您可以使用 string.Split() 来拆分值。
string[] splitIds = ids.split(',');
您只需对它们进行 foreach 并 int.TryParse 每一个即可。之后只需添加到列表中即可。
没关系 - @Splash 比我先一步
List<int> convertIDs = new List<int>;
string[] splitIds = ids.split(',');
foreach(string s in splitIds)
{
convertIDs.Add(int.Parse(s));
}
为了完整起见,您将需要在 for 循环(或 int.Parse() 调用周围)放置 try/catch 并根据您的要求处理错误。您还可以像这样执行 tryparse() :
List<int> convertIDs = new List<int>;
string[] splitIds = ids.split(',');
foreach(string s in splitIds)
{
int i;
int.TryParse(out i);
if (i != 0)
convertIDs.Add(i);
}
要继续之前的答案,只需迭代 Split 返回的数组并转换为新的整数数组即可。下面的 C# 示例:
string[] splitIds = stringIds.Split(',');
int[] ids = new int[splitIds.Length];
for (int i = 0; i < ids.Length; i++) {
ids[i] = Int32.Parse(splitIds[i]);
}
我认为最简单的方法是如前所示进行分割,然后循环遍历值并尝试转换为 int。
class Program
{
static void Main(string[] args)
{
string queryString = "1234,4321,6789";
int[] ids = ConvertCommaSeparatedStringToIntArray(queryString);
}
private static int[] ConvertCommaSeparatedStringToIntArray(string csString)
{
//splitting string to substrings
string[] idStrings = csString.Split(',');
//initializing int-array of same length
int[] ids = new int[idStrings.Length];
//looping all substrings
for (int i = 0; i < idStrings.Length; i++)
{
string idString = idStrings[i];
//trying to convert one substring to int
int id;
if (!int.TryParse(idString, out id))
throw new FormatException(String.Format("Query string contained malformed id '{0}'", idString));
//writing value back to the int-array
ids[i] = id;
}
return ids;
}
}