Handling empty values with FirstOrDefault

Hi,

I am facing an issue about I need to fill a table from another one based in some condition, and I have to do it with linq queries.

I am doing a for each row from dt_main and assign:

For each row in dt_Main:
Assign activity:

row(“a”) = dt.AsEnumerable().Where(Function(key) key(“number”).ToString.Trim.ToLower.Contains(row(“ID”).ToString.Trim)).FirstOrDefault()(“id”)

The issue is when “id” is empty it gives the message error: Object reference not set to an instance of an object.

Do you know how can I handle this issue?

Thanks :slight_smile:

Hi,

How about the following expression?

dt.AsEnumerable().GroupBy(Function(r) r("number").ToString.Trim.Contains(row("id").ToString.Trim)).Select(Function(g) if(g.Key=True,g.First().Item("id").ToString,"")).OrderByDescending(Function(s) s).First()

Regards,

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.