Home > Software engineering >  Set new value for first occurrence of an object
Set new value for first occurrence of an object

Time:10-28

So let's assume I have the following structure of response:

"TestObject": [
    {
        "Created": "2022-10-27T07:17:30.671Z",
        "Name": "NOTTEST",
        "FlowInfo": {
            "Type": "TESTTYPE",
            "ActionRequired": false
        }
    },
    {
        "Created": "2022-10-27T09:54:54.582Z",
        "Name": "TEST",
        "FlowInfo": {
            "Type": "TESTTYPE",
            "ActionRequired": false
        }
    },{
        "Created": "2022-10-27T09:55:55.582Z",
        "Name": "TEST",
        "FlowInfo": {
            "Type": "TESTTYPE",
            "ActionRequired": false
        }
    }],
}

I need to change "ActionRequired" to true for first occurrence in list with "Name"="TEST", all others objects with "Name"="TEST" should stay with false.

Here is my code snippet

var b = testObject
    .OrderBy(d => d.Created)
    .Where(d => d.Name == "TEST")
    .Select(d => new ObjectFlowInfo {
        ActionNeeded = true,
    });

CodePudding user response:

Access the first object with

var b = testObject
    .OrderBy(d => d.Created)
    .First(d => d.Name == "TEST");

and set the value with

b.ActionNeeded = true;

This assumes that at least one object fulfills the condition. If the query may return no object then use

var b = testObject
    .OrderBy(d => d.Created)
    .FirstOrDefault(d => d.Name == "TEST");
if (b is not null) { // or   b != null   or   !(b is null)   in older C# versions.
    b.ActionNeeded = true;
}

Note that you can simplify Where(cond).First/FirstOrDefault() to First/FirstOrDefault(cond). This is also more performing but has the same effect.

Both First and FirstOrDefault select the first object if any and return it as is (and not in a IEnumerable<T> as would Select). If there is no such object, First throws an exception whereas FirstOrDefault returns the default value for that type. I.e., null for a reference type.

CodePudding user response:

It should be as easy as that

if (testObject.Any(x => x.Name == "Test"))
{
     testObject.First(x => x.Name == "Test").ActionRequired = true;
}

  • Related