字符串的处理可以算得是编程中最高频的动作之一,如是否有空的判断,对特定字符的过滤、list、dictionary、list 、List与字符串数字之间的转换等。本文将这些常见的转换总结如下,并给出实例代码。
文章原出处: https://blog.csdn.net/haigear/article/details/142279781
一、判断是否为空
最土最不安全的方法就是判断string变量是否为null或者stringvar==“”,这里不提倡,所以不会将其列为常规的方法之一。
方法一 :IsNullOrEmpty
string.IsNullOrEmpty
众所周知,它判断字符串是否为:null或者string.Empty。如果是如"\t"这样的字符就返回false了,为了达到判断和过滤这些特殊格式字符的这些功能,就要辅以replace、splite()、Trim()和Length来解决长度和过滤空格或者回车符的问题。
方法二: IsNullOrWhiteSpace
string.IsNullOrWhiteSpace
它的功能相当于string.IsNullOrEmpty和str.Trim().Length总和,他将字符串给Char.IsWhiteSpace为ture的任何字符都将是正确的。这个方法会比调用上述两个方法的性能更高而且简洁,所以在判断这个功能时使用起来会更顺手,见下列实例代码:
using System;
public class Example
{
public static void Main()
{
string[] values = {
null, String.Empty, "ABCDE",
new String(' ', 20), " \t ",
new String('\u2000', 10) };
foreach (string value in values)
Console.WriteLine(String.IsNullOrWhiteSpace(value));
}
}
输出结果
// True
// True
// False
// True
// True
// True
如果的输入来自combbox这样的非键盘型输入使用string.IsNullOrEmpty就足够了,但如果是textBox这种键盘输入型控件,或者来自某个文件,用string.IsNullOrWhiteSpace安全性会更高。
文章原出处:https://blog.csdn.net/haigear/article/details/142279781
二、与数组的互转
在C#中,数组和集合(如List)之间的转换是常见的需求。以下是一些常见的转换方法:
1. List 转 Array
方法一:使用 ToArray() 方法
这是最直接的方法,适用于任何实现了 IEnumerable 接口的集合,包括 List。
List<int> myList = new List<int> {
1, 2, 3, 4, 5 };
int[] myArray = myList.ToArray();
方法二:使用 LINQ 的 ToArray() 扩展方法
如果你的项目中已经引用了 System.Linq 命名空间,可以使用 LINQ 的 ToArray() 方法。
using System.Linq;
List<int> myList = new List<int> {
1, 2, 3, 4, 5 };
int[] myArray = myList.ToArray();
2. Array 转 List
方法一:使用 ToList() 方法
这是最直接的方法,适用于任何数组。
int[] myArray = {
1, 2, 3, 4, 5 };
List<int> myList = myArray.ToList();
方法二:使用 Array.ForEach 方法
虽然不常用,但你可以使用 Array.ForEach 方法结合 List 的构造函数来实现转换。
int[] myArray = {
1, 2, 3, 4, 5