2015-04-05 105 views
-1

列表和區分INT和字符串值列表和區分INT和字符串值的字符串值

List<string> input = new List<string> { "1", "2", "three", "4", "five", "eight", "9" }; 

List<int> output1 = new List<int>{}; // keep the list here integer values 
List<string> output2 = new List<string> { }; // keep the list here non numericic values 

請幫我...提前

+0

着想'List output1 = input.Select(int.Parse).ToList()'? – 2015-04-05 09:01:15

+1

@SonerGönül它需要過濾非數值,否則會拋出異常 – 2015-04-05 09:25:15

回答

0

由於通過循環列表bool k=int.TryParse(numberString , out temp);並通過你的值作爲參數,你可以找到的天氣是一個整數或不

List<string> input = new List<string> { "1", "2", "three", "4", "five", "eight", "9" }; 


List<int> output1 = new List<int>{}; // keep the list here integer values 
List<string> output2 = new List<string> { }; // keep the list here non numericic values 

foreach(var temp in input) 
{ 
    bool k=int.TryParse(numberString , out temp); 
    if(k==true) 
    { 
    output1.add(temp) 
    } 
    else 
    { 
    output2.add(temp) 
    } 
} 
+0

這不會構建。 'temp'屬於'string'類型,但是你嘗試將它添加到'output1',它是'List '。您應該引入另一個變量來保存'TryParse'的值,因爲您已經使用它來遍歷(以字符串形式)**和**以包含解析值(作爲int)。 – 2015-04-05 10:26:02

+0

如果我顯示輸出它得到像這樣System.Collection.Generics.List'1 [System.Int32] System.Collection.Generics.List'1 [System.Int32] System.Collection.Generics.List'1 [System。 String] System.Collection.Generics.List'1 [System.Int32] System.Collection.Generics.List'1 [System.String] ............. – Jagan 2015-04-07 01:46:54

4
foreach(string item in input) 
{ 
    int result = 0; 

    if(Int32.TryParse(item, out result)) 
    { 
     output1.Add(result); 
    } 
    else 
    { 
     output2.Add(item); 
    } 
} 
+1

您正在解析該值(不是使用'TryParse'然後'Parse'),並且你的代碼很清晰。我唯一的建議是將'result'移到'foreach'的範圍內,因爲它不需要外部。 +1 – 2015-04-05 10:29:56

+1

感謝您的建議。 – Fatih 2015-04-05 10:59:11

0

我會做這樣的事情:

int outInt; 
var intStringValues = input.Where(o => int.TryParse(o, out outInt)).ToList(); 

List<int> output1 = intStringValues.Select(int.Parse).ToList();  
List<string> output2 = input.Except(intStringValues).ToList(); 

這裏有一個demostrating小提琴:https://dotnetfiddle.net/gVqloX

更可能還不如高性能作爲一個簡單的foreach,但只是爲了做LINQ風格