简体   繁体   English

如何转换清单 <string> 列出 <int> 在C#中使用LINQ将空或空字符串转换为0的地方

[英]How to convert List<string> to List<int> where empty or null string to be converted as 0 using LINQ in C#

How to convert List<string> to List<int> where empty or null string to be converted as 0 using LINQ in C# 如何在C#中使用LINQ将List<string> to List<int>转换List<string> to List<int> ,其中将空字符串或空字符串转换为0

Following LINQ statements will convert the List<sting> to List<int> but do these statements work for above mentioned scenario 以下LINQ语句会将List<sting>转换为List<int>但这些语句对上述情况有效吗

listofIDs.Select(int.Parse).ToList()

var intList = stringList.Select(s => Convert.ToInt32(s)).ToList()

Here's my pitch: 这是我的建议:

        var stringlist = new List<String> { "1", "2", "", null };
        var intList = stringlist.Select(s => { int i; return int.TryParse(s, out i) ? i : 0; }).ToList();
        Debug.Print("{0},{1},{2},{3}", intList[0], intList[1], intList[2], intList[3]);

Test output: 1,2,0,0 测试输出:1,2,0,0

Not dissimilar to the IsNullOrWhiteSpace suggestion. 与IsNullOrWhiteSpace建议没什么不同。 However, it's safer than just using int.Parse unguarded, which will throw an exception if given invalid input. 但是,这比仅使用不受保护的int.Parse更安全,如果输入无效,则将引发异常。

A suggestion for you: TDD! 给您的建议:TDD! Get familiar with one of the many .NET testing frameworks. 熟悉许多.NET测试框架之一。 You can answer questions like yours with another 2-3 lines of code. 您可以使用另外的2-3行代码来回答类似您的问题。

stringList.Select(s => string.IsNullOrEmpty(s) ? 0 : int.Parse(s)).ToList();

or you may try using string.IsNullOrWhiteSpace if you are using .Net framework 4.0 or higher 或者如果您使用的是.Net framework 4.0或更高版本,则可以尝试使用string.IsNullOrWhiteSpace

stringList.Select(s => string.IsNullOrWhiteSpace(s) ? 0 : int.Parse(s)).ToList();

For example: 例如:

List<string> stringList = new List<string> { "1", "2", "3", "    ", "", "4" };
List<int> newListOfInt = stringList.Select(s => string.IsNullOrWhiteSpace(s) ? 
                                                  0 : int.Parse(s)
                                           ).ToList();

尝试这个:

listofIDs.Select(id => string.IsNullOrEmpty(id)? 0 : int.Parse(id)).ToList();
var intList = stringList.Select(s => (String.IsNullOrEmpty(s))? 0 : Convert.ToInt32(s)).ToList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM