English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ Advantages

To understand why we should use LINQ, let's look at some examples. Suppose you want to find a list of teenage students from a series of Student objects.

in C#2.0 before, we must use the 'foreach' or 'for' loop to traverse the collection to find a specific object. For example, we must write the following code to find the list of students with ages in12to20 years (adolescents)}13to19Find all student objects in a series of students aged

In C#1.0, using for loop to find elements in the collection
class Student
{
    public int StudentID { get; set; }
    public String StudentName { get; set; }
    public int Age { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        Student[] studentArray = { 
            new Student() { StudentID = 1, StudentName = "John",     Age = 18 },
            new Student() { StudentID = 2, StudentName = "Steve",     Age = 21 },
            new Student() { StudentID = 3, StudentName = "Bill",     Age = 25 },
            new Student() { StudentID = 4, StudentName = "Ram" ,     Age = 20},
            new Student() { StudentID = 5, StudentName = "Ron" ,     Age = 31 },
            new Student() { StudentID = 6, StudentName = "Chris",     Age = 17 },
            new Student() { StudentID = 7, StudentName = "Rob", Age = 19  },
        };
        Student[] students = new Student[10];
        int i = 0;
        foreach (Student std in studentArray)
        {
            if (std.Age > 12 && std.Age < 20)
            {
                students[i] = std;
                i++;
            }
        }
    }
}

The use of for loop is麻烦, not maintainable and readability is poor. C#2.0, as shown below.

    Example: Using a delegate from C#2Find elements in the collection at index 0

delegate bool FindStudent(Student std);
class StudentExtension
{ 
    public static Student[] where(Student[] stdArray, FindStudent del)
    {
        int i = 0;
        Student[] result = new Student[10];
        foreach (Student std in stdArray)
            if (del(std))
            {
                result[i] = std;
                i++;
            }
        return result;
    }
}
    
class Program
{
    static void Main(string[] args)
    {
        Student[] studentArray = { 
            new Student() { StudentID = 1, StudentName = "John",     Age = 18 }; ,
            new Student() { StudentID = 2, StudentName = "Steve",     Age = 21 }; ,
            new Student() { StudentID = 3, StudentName = "Bill",     Age = 25 }; ,
            new Student() { StudentID = 4, StudentName = "Ram" ,     Age = 20 }, ,
            new Student() { StudentID = 5, StudentName = "Ron" ,     Age = 31 }; ,
            new Student() { StudentID = 6, StudentName = "Chris",     Age = 17 }; ,
            new Student() { StudentID = 7, StudentName = "Rob", Age = 19  }; ,
        };
        Student[] students = StudentExtension.where(studentArray, delegate(Student std) {
                return std.Age > 12 && std.Age < 20;
            });
        }
    }
}

Therefore, using C#2.0, you can take advantage of the benefits of delegates to find students that meet any condition. You do not need to use a for loop to find students using different criteria. For example, you can use the same delegate function to find students with StudentId of5or students whose name is Bill, as shown below:

Student[] students = StudentExtension.where(studentArray, delegate(Student std) {
        return std.StudentID == 5;
    });
//In addition, use the same delegate to use other conditions
Student[] students = StudentExtension.where(studentArray, delegate(Student std) {
        return std.StudentName == "Bill";
    });

The C# team believes that they still need to make the code more compact and readable. Therefore, they introduced in C#3.0 introduced extension methods, lambda expressions, expression trees, anonymous types, and query expressions. You can use C#3.0 provides these features (which are the building blocks of LINQ) to query different types of collections and get result elements in a single statement.

The following example demonstrates how to use LINQ queries with lambda expressions to find specific students from a student collection.

Example: LINQ
class Program
{        static void Main(string[] args)
    {        
          Student[] studentArray = { 
                    new Student() { StudentID = 1, StudentName = "John", age = 18 }; ,
                    new Student() { StudentID = 2, StudentName = "Steve", age = 21 }; ,
                    new Student() { StudentID = 3, StudentName = "Bill", age = 25 }; ,
                    new Student() { StudentID = 4, StudentName = "Ram", age = 20 }, ,
                    new Student() { StudentID = 5, StudentName = "Ron", age = 31 }; ,
                    new Student() { StudentID = 6, StudentName = "Chris", age = 17 }; ,
                    new Student() { StudentID = 7, StudentName = "Rob", age = 19  }; ,
           };
         // Use LINQ to find adolescent students
         Student[] teenAgerStudents = studentArray.Where(s => s.age > 12 && s.age < 20).ToArray();       
        // Use LINQ to find the first student named Bill 
        Student bill = studentArray.Where(s => s.StudentName == "Bill").FirstOrDefault();        
        // Use LINQ to find StudentID of5student        
        Student student5 = studentArray.Where(s => s.StudentID == 5).FirstOrDefault();
    }
}

As shown in the example above, we specify different conditions using LINQ operators and lambda expressions in a single statement. Therefore, LINQ makes the code more compact and readable, and can also be used to query different data sources. For example, if you have a student table in a database instead of the student object array above, you can still use the same query to find students using Entity Framework.

Advantages of LINQ

  • Familiar language (Familiar language): Developers do not need to learn a new query language for each type of data source or data format.

  • Less coding (Less coding): Compared to more traditional methods, it reduces the amount of code to be written.

  • Readable code (Code Readability): LINQ makes the code more readable, so other developers can easily understand and maintain it.

  • Standardized way of querying multiple data sources (Standardized way of querying multiple data sources): The same LINQ syntax can be used to query multiple data sources.

  • Compile-time safety of queries (Compile-time safety of queries): It provides type checking of objects at compile time.

  • IntelliSense Support (Intelligent Perception Support): LINQ provides IntelliSense for generic collections.

  • Shaping data (Data Shape): You can retrieve data in different shapes.