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).
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.
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.
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.
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.
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());
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With