Use Linq Aggregate to reverse a string in CSharp

Description

The following code shows how to use Linq Aggregate to reverse a string.

Example


     /*from  www .ja v a2  s  . c o m*/
using System;
using System.Collections.Generic;
using System.Linq;

    class Program
    {
        private static string ReverseString(string sentence)
        {
            List<string> words = new List<string>(sentence.Split(' ').ToList());

            return words.Aggregate((a, b) => b + " " + a);            
        }

        static void Main(string[] args)
        {
            string sentence = "this is a test";
            string result = ReverseString(sentence);
            Console.WriteLine(result);
        }        
    }

The code above generates the following result.





















Home »
  C# Tutorial »
    LINQ »




Operator
Select
Where
OrderBy
Group
Join
Let
LINQ