0

I have a translation map that looks like this:

enter image description here

I have a query that goes and grabs the translations from each one of the rows above:

var fieldType="Gender";
var translateFrom = "F";

IEnumerable<DataRow> row = from dataRow in translations.AsEnumerable()
                           where dataRow.Field<string>("TranslateFrom").ToLower().Trim() == translateFrom
                                 && dataRow.Field<string>("FieldType").ToLower().Trim() == fieldType
                           select dataRow;

var translateTo = (string)row.FirstOrDefault()?["TranslateTo"];

However for some reason I am getting exceptional behavior when it iterates through this data row:

enter image description here

If for example I set the translateFrom to empty string:

var translateFrom="";

Then I get a null reference exception on this line:

var translateTo = (string)row.FirstOrDefault()?["TranslateTo"];

The goal is to have string.Empty be translated to U as seen above in the translation.

What am I doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alex Gordon
  • 191
  • 11
  • Is the `TranslateFrom` value null (i.e. `DBNull.Value`)? If so, I'd expect a null reference exception at `dataRow.Field("TranslateFrom").ToLower()`. What about trying `dataRow["TranslateFrom"].ToString().ToLower()` instead? I'd expect this to work as DBNull.Value.ToString() is an empty string. – Joe Oct 29 '18 at 20:55
  • `row` should be named `rows` since it represents a collection. – Rufus L Oct 29 '18 at 20:57
  • @joe thats an awesome idea, but what happens is the collection `IEnumerable row ` is empty – Alex Gordon Oct 29 '18 at 21:00
  • @AlexGordon - Take FirstOrDefault and check for null – Joe Oct 29 '18 at 21:14

1 Answers1

1

You can make a little extension method like this:

public static class MyExtensions {
    public static string NullSafe(this string s){
        if(s == null){
            return "";
        }
        return s;
    }   
}

And then use it like this to convert null data to empty string:

dataRow.Field<string>("TranslateFrom").NullSafe().ToLower().Trim()
Leo Bartkus
  • 1,925
  • 13
  • 17