-1

I have a datatable. I am getting distinct value of column from below code.

AllFields is my datatable.

var distinctIds = AllFields.AsEnumerable()
    .Select(s => new
    {
        id = s.Field<string>(ColumnName),
    })
    .Distinct()
    .ToList();

however I want to get distinct value of a column with where condition on same column. I have tried below thing.

var distinctIds = AllFields.AsEnumerable()
    .Select(s => new
    {
        id = s.Field<string>(ColumnName),
    })
    .Distinct()
    .Where(f => f.id.Contains(TxtStringSearchInput.Text))
    .ToList();

it is showing me below error on run time.

nullreferenceexception error . {"Object reference not set to an instance of an object."}

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Rohit
  • 69
  • 1
  • 7
  • Psychic debugging says that one of your rows has a `null` in it and the Contains is failing. However, without an actual error message my psychic skills have been known to be lacking. – Steve Mitcham Apr 23 '15 at 15:30
  • @SteveMitcham is probably correct - check out the linked question for _lots_ of information about this error and how to track down where it is. – James Thorpe Apr 23 '15 at 15:33

2 Answers2

3

As you are getting NRE. It looks like one of the value is coming null so you should be checking for null as well in Where():

var distinctIds = AllFields.AsEnumerable()
.Select(s => new
{
    id = s.Field<string>(ColumnName),
})
.Distinct()
.Where(f => f.id !=null && f.id.Contains(TxtStringSearchInput.Text))
.ToList();
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
3

Since you're getting a null reference exception on the second call, and the only difference is that you're calling Contains on the id field, it is most likely that the id field is null for one of your comparisons.

Try checking for null before calling Contains, for example:

var distinctIds = AllFields
    .AsEnumerable()
    .Select(s => new {id = s.Field<string>(ColumnName),})
    .Distinct()
    .Where(f =>
        f.id != null &&
        f.id.Contains(TxtStringSearchInput.Text))
    .ToList();
Rufus L
  • 36,127
  • 5
  • 30
  • 43