从字符串中分离出整数
假设我有一个网页,该网页当前通过url参数接受单个ID值:
http://example.com/mypage.aspx?ID=1234
我想将其更改为接受ID列表,如下所示:
http://example.com/mypage.aspx?IDs=1234,4321,6789
因此,可以通过context.Request.QueryString [" IDs"]将其作为字符串提供给我的代码。将字符串值转换为List <int>的最佳方法是什么?
编辑:我知道如何在逗号上执行.split()以获得字符串列表,但是我问是因为我不知道如何轻松地将该字符串列表转换为int列表。它仍然在.Net 2.0中,因此没有lambda。
解决方案
回答
从URL中提取值后,可以使用string.Split()拆分值。
string[] splitIds = ids.split(',');
回答
我所能想到的就是遍历字符串列表(通过执行拆分得到的字符串),然后对它们进行类似int.TryParse()的操作,然后将它们放入新的List <int >`。将其封装在一个不错的辅助方法中,不会太恐怖。
回答
我们只需要遍历它们并进行int.TryParse解析它们中的每一个即可。之后,只需将其添加到列表中即可。
没关系@Splash击败了我
回答
我们可以从数组实例化List <T>。
VB.NET:
Dim lstIDs as new List(of Integer)(ids.split(','))
尽管如果数组包含非int元素,则容易发生转换错误
回答
首先想到的是split,但是它返回一个数组,而不是List;
我们可以尝试类似的方法:
List<int> intList = new List<int>; foreach (string tempString in ids.split(',') { intList.add (convert.int32(tempString)); }
回答
这样的事情可能会起作用:
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<int> convertIDs = new List<int>; string[] splitIds = ids.split(','); foreach(string s in splitIds) { convertIDs.Add(int.Parse(s)); }
为了完整起见,我们将需要在for循环(或者int.Parse()调用)周围放置try / catches并根据需要处理错误。我们也可以像这样进行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返回的数组并将其转换为新的int数组即可。下面的示例在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]); }
回答
如果我们喜欢功能样式,可以尝试类似
string ids = "1,2,3,4,5"; List<int> l = new List<int>(Array.ConvertAll( ids.Split(','), new Converter<string, int>(int.Parse)));
没有lambda,但是我们确实具有Converters和Predicates以及可以通过方法实现的其他优点。
回答
我认为最简单的方法是如前所示拆分,然后遍历值并尝试转换为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; } }
回答
提供明确答案的人并没有冒犯,但很多人似乎在回答问题,而不是解决问题。我们需要多个ID,因此我们可以这样做:
http://example.com/mypage.aspx?IDs=1234,4321,6789
问题在于,这不是一种可靠的解决方案。将来,如果我们想要多个值,如果它们带有逗号,该怎么办?更好的解决方案(这在查询字符串中完全有效)是使用具有相同名称的多个参数:
http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789
然后,无论我们使用什么查询字符串解析器,都应该能够返回ID列表。如果它不能处理这个问题(并且也可以处理分号而不是"&"号),那么它就坏了。
回答
最终代码段应采用我希望从所有建议中得到的最好的代码段:
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。我只喜欢Cfor提出问题,因为它们会吸引更多的听众,而且我也能说流利的话。
回答
我看到我的答案来得很晚,即其他几个人也写了相同的答案。因此,我提出了一种使用正则表达式来验证和分割字符串的替代方法。
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(); } }