Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change one field in an array using linq

Tags:

c#

linq

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!

like image 205
Arthurdent510 Avatar asked Feb 20 '12 21:02

Arthurdent510


People also ask

How do I return a single value from a list using LINQ?

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().

Can LINQ use with Array?

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.

What is LINQ in C# with example?

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.


2 Answers

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.


Let me quantify "sort of linq". ForEach is not Linq, but a method on List<T>. However, the syntax is similar to Linq.
like image 184
Joe Avatar answered Sep 22 '22 03:09

Joe


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).

like image 34
Richard Avatar answered Sep 21 '22 03:09

Richard