Home > Back-end >  How can i simplify this into one line
How can i simplify this into one line

Time:02-01

portalSelectslist.FirstOrDefault(x => x.PortalId == item.PortalId).AccessTypePortalId = item.AccesstypePortalId;
                portalSelectslist.FirstOrDefault(x => x.PortalId == item.PortalId).Isselected = true;

Update an item from list i update each property in each line instead of that how can i update both in a line

CodePudding user response:

Use a temporary variable. So you don't have to query the list twice and it's easier to read.

var temp = portalSelectslist.FirstOrDefault(x => x.PortalId == item.PortalId);
if(temp != null)
{
    temp.AccessTypePortalId = item.AccesstypePortalId;
    temp.Isselected = true;
}

CodePudding user response:

You can't or probably shouldn't. Just because it's on a single line, doesn't make it better code.

The following is much more readable/maintainable.

var portal = portalSelectslist
    .FirstOrDefault(x => x.PortalId == item.PortalId);

if (portal != null) {
    portal.AccessTypePortalId = item.AccesstypePortalId;
    portal.Isselected = true;
}

UPDATE Technically you could do this in a single "line" but don't. This code is not easy to read or understand and therefore much less maintainble.

portalSelectslist.Where(x => x.PortalId == item.PortalId).ToList().ForEach(s => { s.AccessTypePortalId = item.AccesstypePortalId; s.Isselected = true });

Just because you can, doesn't mean you should.

The code looks like it's updating all values that match the where clause. This is not the intent you're trying to convey to whomever is reading the code, you only want to update a single value.

The first thing to worry about writing code (after getting it working) is readability and maintainability.

  •  Tags:  
  • Related