I have an array of objects, where one field is a boolean field called includeInReport. In a certain case, I want to default that to always be true. I know it's as easy as doing this:
foreach (var item in awards)
{
item.IncludeInReport = true;
}
But is there an equilivent way to do this with linq? It's more to satisfy my curiosity then anything... My first thought was to do this...
awards.Select(a => new Award{ IncludeInReport = true, SomeFiled = a.SomeField, .... }
But since I have a few fields in my object, I didn't want to have to type out all of the fields and it's just clutter on the screen at that point. Thanks!
var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().
LINQ to String Array means writing the LINQ queries on string array to get the required data. If we use LINQ queries on string arrays, we can get the required elements easily without writing the much code.
LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.
ForEach is sort of linq:
awards.ForEach(item => item.IncludeInReport = true);
But Linq is not about updating values. So you are not using the right tool.
List<T>
. However, the syntax is similar to Linq.
Here's the correct code:
awards = awards.Select(a => {a.IncludeInReport = true; return a;});
LINQ follows functional programming ideas and thus doesn't want you to change (mutate) existing variables.
So instead in the code above we generate a new list (haven't changed any existing values) and then overwrite our original list (this is outside LINQ so we no longer care about functional programming ideas).
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