Home

LINQ and the String Class

     

Introduction

In case you have not paid attention to it in the past, the String starts as follows:

public sealed class String : IComparable, 
    ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, 
    IEnumerable, IEquatable<string>
   

As you can see, the String class implements:

  • The IEnumerable interface. This means that it is already ready for all possible operations of the LINQ
  • The IEnumerable<char> interface. This results in a string being a collection of characters. Consequently, all normal collection operations can be performed on a string and each character or symbol is treated as an item
  • The IComparable and the IComparable<string> interfaces. This gives the ability to compare two strings

Based on this, the String class holds a special position in LINQ. If you create a LINQ statement whose select expression produces a string value, the String class makes available its properties and methods so you can use them to refine your where statement.

Concatenating the Results of a Select Statement

We saw how you can use one value that is a member of an object of a class as produced by a select statement:

var lastNames = from n
                in empls 
                select n.LastName;

To add other values to the select statement, that is, to access more that one member of the class, you can concatenate them. The String class provides various solutions.

The String class is equipped with the Concat() method that is overloaded with 10 versions. You can use any of those versions to add strings. Here is an example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        employees = new Employee[]
        {
            new Employee(971974, "Patricia", "Katts", 24.68M),
            new Employee(208411, "Raymond", "Kouma", 20.15M),
            new Employee(279374, "Hél�ne", "Mukoko", 15.55M),
            new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
            new Employee(971394, "Gertrude", "Monay", 20.55M)
        };

        var empls = from staffMembers
                    in employees
                    select string.Concat(staffMembers.EmployeeNumber.ToString(), ", ",
                                          staffMembers.FirstName, " ",
                                          staffMembers.LastName, ", ",
                                          staffMembers.HourlySalary.ToString());

        foreach (var empl in empls)
            Console.WriteLine(empl);
        Console.WriteLine();
        return 0;
    }
}

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public decimal HourlySalary;

    public Employee(int number = 0,
                       string firstName = "John",
                       string lastName = "Doe",
                       decimal salary = 0M)
    {
        EmployeeNumber = number;
        FirstName = firstName;
        LastName = lastName;
        HourlySalary = salary;
    }

    internal string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

This would produce:

Employees

Alternatively, you can use the + operator that is overloaded in the string class. Here is an example:

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        employees = new Employee[]
        {
            new Employee(971974, "Patricia", "Katts", 24.68M),
            new Employee(208411, "Raymond", "Kouma", 20.15M),
            new Employee(279374, "Hél�ne", "Mukoko", 15.55M),
            new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
            new Employee(971394, "Gertrude", "Monay", 20.55M)
        };

        var empls = from staffMembers
                    in employees
                    select staffMembers.LastName + ", " + staffMembers.FirstName;

        foreach (var empl in empls)
            Console.WriteLine(empl);
        Console.WriteLine();
        return 0;
    }
}

This would produce:

Employees

Two other solutions consist of using either the Format() of the Join() methods (of the String class).

Checking for String Equality

Like all classes of the .NET Framework, the String class inherits the Equals() method of the Object class. This makes it possible to compare two strings for equality. Besides the Equals() method, the == operator is overloaded in the String class and has the same effect. Here is an example of using it:

using System;
using System.Linq;
using System.Collections.Generic;

public class Exercise
{
    public static int Main()
    {
        var names = new[]
    	{
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patrick",
            "Patrick", "Raul", "David", "Paulette"
    	};

        var name = from n
                   in names
                   where n == "Patrick"
                   select n;

        foreach (var member in name)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Employees

If you are working on a class, you can apply the equality operator on one of its properties. Here is an example:

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        employees = new Employee[]
	{
            new Employee(971974, "Patricia", "Katts", 24.68M),
            new Employee(208411, "Raymond", "Kouma", 20.15M),
            new Employee(279374, "Hél�ne", "Mukoko", 15.55M),
            new Employee(707912, "Bertrand", "Yamaguchi", 24.68M),
            new Employee(294800, "Peter", "Mukoko", 18.85M),
            new Employee(971394, "Gertrude", "Monay", 20.55M)
    	};

        var fullNames = from empls
                        in employees
                        where empls.LastName == "Mukoko"
                        select empls.LastName + ", " + empls.FirstName;

        foreach (var empl in fullNames)
            Console.WriteLine(empl);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Employees

On the other hand, to find out if two strings are not equal, you can use the != operator.

Checking the Starting Sub-String

The String class is equipped with various types of methods to work on sub-strings. To get a list of strings that start with a certain letter or a sub-string, you can call the StartsWith() method. This is a Boolean method that is overloaded with three versions. One of the versions takes one argument that is the sub-string to find at the beginning of the string that calls it. Here is an example:

public class Exercise
{
    public static int Main()
    {
        var name = new[]
    	{
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patricia",
            "Henriette", "Raul", "David", "Paulette"
    	};

        var names = from n
                    in name
                    where n.StartsWith("P")
                    select n;

        foreach (var member in names)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Starts With

The String.StartsWith() method returns true if the variable that called it starts with the argument. You can negate the result to find the strings that don't start with the argument. To do this, apply the ! operation. Here is an example:

public class Exercise
{
    public static int Main()
    {
        var name = new[]
    	{
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patricia",
            "Henriette", "Raul", "David", "Paulette"
    	};

        var names = from n
                    in name
                    where !n.StartsWith("P")
                    select n;

        foreach (var member in names)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Starts With

To make the expression easy to read, you should include it in parentheses. Here is an example:

public class Exercise
{
    public static int Main()
    {
        var name = new[]
	{
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patricia",
            "Henriette", "Raul", "David", "Paulette"
    	};

        var names = from n
                    in name
                    where !(n.StartsWith("P"))
                    select n;

        foreach (var member in names)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

Checking the Ending Sub-String

To get a list of strings that end with a certain letter or sub-string, you would call the String.EndsWith() method. Here is an example:

public class Exercise
{
    static Employee[] employees;

    public static int Main()
    {
        var name = new[]
    	{
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patricia",
            "Henriette", "Raul", "David", "Paulette"
    	};

        var names = from n
                    in name
                    where n.EndsWith("ette")
                    select n;

        foreach (var member in names)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Ends With

To negate this operation, apply the ! operator to it.

Checking the Existence of a Sub-String

In the same way, to get a select list of strings that contain a certain symbol or sub-string, you can call the String.Contains() method as follows:

public class Exercise
{
    public static int Main()
    {
        var name = new[]
        {
            "Hermine", "Patrick", "Hank", "Bertine",
            "Julius", "Thomas", "Jeannette", "Patricia",
            "Henriette", "Raul", "David", "Paulette"
        };

        var names = from n
                    in name
                    where n.Contains("au")
                    select n;

        foreach (var member in names)
            Console.WriteLine(member);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Contains

Because the String.Contains() method is Boolean, to negate its result, you can precede it with the ! operator.

 
 

Previous Copyright © 2010-2016, FunctionX Next