문제

자가 웹 페이지는 현재 단일 ID 값 url 을 통해 매개변수:
http://example.com/mypage.aspx?ID=1234

나는 그것을 변경하고 싶을 받아들일 목록 의 id,다음과 같다:
http://example.com/mypage.aspx?IDs=1234,4321,6789

사용할 수 있도록 내 코드로를 통해 문자열 context.요청을 합니다.쿼리 문자열["Id"]. 는 가장 좋은 방법은 무엇인하는 문자열 값으로 목록<int>?

편집: 난 어떻게 할 수 있습니다.split()에 쉼표의 목록을 문자열을,하지만 난 알 수 없기 때문에 나는 어떻게 변환하는 문자열 목록 int 목록입니다.이것은 여전히습니다.Net2.0,그래서 람다.

도움이 되었습니까?

해결책

어떤 공격을 제공하는 사람들에게 명확한 답변을,그러나 많은 사람들을 당신의 질문에 대답을 대신 해결의 문제입니다.당신이 원하는 여러 개의 Id 당신이 생각하는,그래서 당신이 이:

http://example.com/mypage.aspx?IDs=1234,4321,6789

문제는 이 강력한 솔루션입니다.미래에,당신이 원하는 경우 여러 값,당신은 무엇이 있는 경우에는 쉼표?더 나은 솔루션(이 완벽하게 유효한 쿼리에서 문자열),은 여러 매개 변수를 사용하여 동일한 이름:

http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789

그런 다음,어떤 쿼리 문자열을 파서 사용할 수 있어야의 목록을 반환합니다.할 수 없는 경우에는 핸들이(그리고 또한 취급 세미콜론 대의 앰퍼샌드),다음은 깨졌습니다.

다른 팁

이런 작동 수 있습니다:

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);
}

인스턴스화할 수 있 목록<T> 에서 훌륭한 기능들을 가지고 있습니다.

VB.NET:

Dim lstIDs as new List(of Integer)(ids.split(','))

이 경향을 주는 오류만을 경우 배열이 포함되 non-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)));

아 람다,하지만 당신은 변환기 및 조건자와 다른 것들에서 만들 수 있는 방법이 있습니다.

나는 나의 답변 온라,즉여러 가지 다른 작성했 같습니다.그러므로 나는 현재 대체 방법을 사용하여 정기적인 표현을 검증하고 나눌 문자열입니다.

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

라고 기대했을 할 수 있 그것은 하나 또는 두 개의 라인의 코드는 인라인 요소입니다.하나의 라인을 만들 문자열을 배열과 희망을 찾아가에 프레임워크에서는 이미 알고하지 않을 처리 가져오기 위 목록<int> 할 수 있는 손잡이의 캐스팅을 맞출수 있습니다.하지만 만약 내가 그것을 이동하는 방법은 다음 난 것입니다.고 그렇다,나는 사용 VB.나는 그냥아보세요 C#에 대한 질문하기를 그들을 얻을 것이 더 큰 고객 그리고 나는 대로 유창하게 구사한다.

분할은 첫 번째는,그러나 그 배열을 반환합니다,목록을 사용할 수 없습니다;당신이 시도할 수 있습 같은 것:


List<int> intList = new List<int>;

foreach (string tempString in ids.split(',')
{
    intList.add (convert.int32(tempString));
}

당신이 사용할 수 있는 문자열입니다.Split()을 분할한 값를 추출하면서 그들을 URL.

string[] splitIds = ids.split(',');

당신은 단지 foreach 를 통해 그들과 int.TryParse 각각 그 중 하나입니다.그 후 그냥 목록에 추가.

걱정-@스플래시 저를 이길을 그

List<int> convertIDs = new List<int>;
string[] splitIds = ids.split(',');
foreach(string s in splitIds)
{
    convertIDs.Add(int.Parse(s));
}

완전성을 위해 당신을 두고 싶을 것이다 try/을 잡는 주변에 대한 루프(또는 주변 int.Parse()호출에)오류를 처리 기반으로 귀하의 요구 사항입니다.을 할 수 있습 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);
}

에 계속하기 이전에 응답,단순히 반복을 통해 배열을 반환에 의해 분할 및로 변환하여 새로운 배열의 수.이 샘플에서 아래는 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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top