0

I'm trying to find out if it is possible to update 2 or more fields using linq.

I've found this example that shows 1 property updated, but I'm unsure as to how it could be converted.

listOfCompany.FirstOrDefault().Name = "Whatever Name"; // desc = "Whatever desc"

Any ideas?

0

5 Answers 5

3

Just pull back the entire entity instead of a single property.

var myEntity = listOfCompany.FirstOrDefault();
if(myEntity!=null)
{
   myEntity.Name = "Blah";
   myEntity.Something = "Blah 2";
}
Sign up to request clarification or add additional context in comments.

Comments

1

While you want to update a list of objects, you can do the following:

var company = listOfCompany.FirstOrDefault();
company.Name = "Name"; 
company.Number = 14377;
company.MyProp = obj;

Comments

1
var x = listOfCompany.FirstOrDefault();
x.Name = "Whatever Name";
x.Desc = "Whatever Desc";

You could certainly do something like this:

listOfCompany.FirstOrDefault().Name = "Whatever Name";
listOfCompany.FirstOrDefault().Desc = "Whatever Desc";

But I think that, at best, it looks odd.

Note that FirstOrDefault() could return null if listOfCompany does not have any items, so be careful about assuming that it is safe to reference the item returned FirstOrDefault() and then try to set properties on it.

I'm not aware of a way to set both properties at once.

Comments

1

I would advise against it because its rather confusing. Its much clearer to just update each field one at a time. But here is is:

listOfCompany.Select(c => new Company(){Name = "NewName", Number = 666, desc = c.desc}).FirstOrDefault();

Comments

1

Linq is for querying, not updating. Your example is the equivalent of

var temp = listOfCompany.FirstOrDefault()
temp.Name = "Whatever Name";   
// desc = "Whatever desc"

obviously the second line is a basic property set - it has nothing whatsoever to do with Linq. In order to update properties (whether one or more) you need a reference to the item, which you can get with Linq:

var company = listOfCompany.FirstOrDefault()
company.name = "Whatever Name";
company.desc = "Whatever desc";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.