1
\$\begingroup\$

I've written some code to read a column of data from a dataset called AltIds. The values are nullable. My code is written to find all the values in the column that are not null and write them to an array.

Guid[] altIds = myDataSet.Tables[0].AsEnumerable()
  .Select(row => row.Field<Guid?>("AltId"))
  .Where(x => x.HasValue)
  .Select(x=>x.Value)
  .ToArray();

The code works, but it seems a bit complicated. Is there a better way to do this?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

What you have is fine. You could restructure it to eliminate one of the selects, but then you would repeat yourself with the row.

var altIds = myDataSet.Tables[0].AsEnumerable()
                 .Where(row => row.Field<Guid?>("AltId").HasValue)
                 .Select(row => row.Field<Guid?>("AltId").Value)
                 .ToArray();

You could rewrite it in query expression syntax, but that's only less complicated if you find fluent syntax more so.

var altIds = (from row in myDataSet.Tables[0].AsEnumerable()
             let x = row.Field<Guid?>("AltId")
             where x.HasValue
             select x.Value).ToArray();

Either way, it's six in one hand, half a dozen in the other. I find your code readable, and it passes the "does what it is supposed to" test, so I wouldn't worry about this snippet.

\$\endgroup\$
0
\$\begingroup\$

This is terribly nit picky, but the whitespace is inconsistent. Give this line some breathing space.

.Select(x=>x.Value)

In a larger sample of code, this kind of thing becomes hard to read.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.