Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Your Favorite LINQ-to-Objects Queries [closed]

Tags:

With LINQ, a lot of programming problems can be solved more easily - and in fewer lines of code.

What are some the best real-world LINQ-to-Objects queries that you've written?

(Best = simplicity & elegance compared to the C# 2.0 / imperative approach).

like image 388
Joe Albahari Avatar asked Feb 04 '09 08:02

Joe Albahari


People also ask

What type of objects can you query using LINQ?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API. In a basic sense, LINQ to Objects represents a new approach to collections.

Does LINQ select return new object?

While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.

What are the uses of LINQ to objects?

In a nutshell, LINQ to Objects provides the developer with the means to conduct queries against an in-memory collection of objects. The techniques used to query against such collections of objects are similar to but simpler than the approaches used to conduct queries against a relational database using SQL statements.

Which of the following supports LINQ queries?

You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support is also provided by third parties for many Web services and other database implementations.


2 Answers

Filter out null items in a list.

var nonnull = somelist.Where(a => a != null);

Create a dictionary where the key is the value of a property, and the value is the number of times that property appears in the list.

var countDictionary = somelist
    .GroupBy(a => a.SomeProperty)
    .ToDictionary(g => g.Key, g => g.Count());
like image 50
Cameron MacFarland Avatar answered Oct 31 '22 15:10

Cameron MacFarland


LINQ is merely the addition of some functional programming concepts to C#/VB. Hence, yes, most things tend to get much easier. C# 2.0 actually had some of this -- see the List methods, for instance. (Although, anonymous method syntax in C# 2.0 was too verbose.)

Here's one little example:

static readonly string badChars = "!@#$%^&*()";
bool IsUserNameValid(string userName) {
  return userName.Intersect(badChars).Any();
}
like image 32
MichaelGG Avatar answered Oct 31 '22 14:10

MichaelGG