2015-04-05 120 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风格