0perator 0perator - 1 year ago 64
C# Question

Set values order based off other values logic

How can I more efficiently check for null values and set their order accordingly?

I have 3 fields (1, 2, 3) and I need to do a check to see if any of the string values are null and if so I need to move the respective value up to the next spot so if 2 is null but 3 is not I will need to move 3 into 2's spot.

My original thought was to do this with a series of if statements however after starting down that road I'm learning that my list of if statements is going to be substantial so I'm looking for a better way to preform this check and set my values.

if (string.IsNullOrEmpty(field1))
fields.SetField("Field1", field1);
fields.SetField("Field2", field2);

If I continued down the above route I would have to also preform a check for field 2 and 3 and etc... for each initial check.

Answer Source

Maybe you could use this logic:

string firstNotNull = field1 ?? field2 ?? field3;
if (string.IsNullOrEmpty(field1)) fields.SetField("Field1", firstNotNull);
if (string.IsNullOrEmpty(field2)) fields.SetField("Field2", firstNotNull);
if (string.IsNullOrEmpty(field3)) fields.SetField("Field3", firstNotNull);

But the logic is not entirely clear. Do you also want to overwrite Field3 with a value from Field1 if the Field3 is null and Field1 not?

Maybe this generic approach is what you're looking for:

var stringColumns = table.Columns.Cast<DataColumn>().Where(c => c.DataType == typeof(string)).ToList();
foreach (DataRow row in table.Rows)
    for (int i = 0; i < stringColumns.Count; i++)
        string field = row.Field<string>(i);
        if (string.IsNullOrEmpty(field))
            // check all after this:
            for (int ii = i + 1; ii < stringColumns.Count; ii++)
                string nextField = row.Field<string>(ii);
                if (!string.IsNullOrEmpty(nextField))
                    row.SetField(i, nextField);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download