个性化阅读
专注于IT技术分析

LINQ转字符串

点击下载

本文概述

将LINQ转换为字符串无非就是在String上编写LINQ查询, 以从字符串序列中获取所需的数据。在LINQ中, 我们可以对字符串以及传统的字符串函数和正则表达式编写查询, 以使用LINQ对字符串执行所需的操作。

LINQ到字符串的语法

编写LINQ查询的语法为:

var result = from s in str.ToLowerInvariant().Split()

在上面的语法中, 我们在String上编写了LINQ查询, 以获取不同的元素。

LINQ转换为字符串的示例

这是在String上编写LINQ查询以将String拆分为C#中的单词的示例。

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Programme2
    {
        static void Main(string[] args)
        {
//create a string 'str1' 
            string str1 = "Welcome     to   Java T Point.Com";
//here StringSplitOptions.RemoveEmptyEntries() is used to remove the spaces between the words.
            var result = from s in str1.ToLowerInvariant().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
            select s;
            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
                Console.ReadLine();
        }
    }
}

在上面的示例中, 我们在LINQ中编写了简单查询, 以将字符串” str”拆分为多个单词。在这里, ” str”字符串对象在单词之间包含许多空格, 为了删除这些空格, 我们使用了” StringSplitOptions.RemoveEmptyEntries”属性。如果我们使用传统编码, 则需要编写大量代码以拆分String并删除单词之间的空格。

输出

LINQ转字符串

这就是我们可以对字符串使用LINQ查询以从字符串中获取所需数据的方式。


赞(0)
未经允许不得转载:srcmini » LINQ转字符串

评论 抢沙发

评论前必须登录!