Inkey
Inkey

Reputation: 2207

LINQ from DataTable Enumeration yielded no results

I have the following statement which when i run it i get

Enumeration yielded no results

 var striko4goodproduct = from myrow in GoodProduct.AsEnumerable()
                          where myrow.Field<string>("MachineID") == "Striko 4"
                          group myrow by myrow.Field<string>("MachineID") == "Striko 4" into g
                          select new
                          {
                            TotalGood = g.Sum(x => x.Field<int?>("VIngot") ??
                                                   0 + x.Field<int?>("Heads") ??
                                                   0 + x.Field<int?>("Risers") ?? 0)
                          };

Is it possible to have it return 0 instead of this message?

Sometimes there is going to be values in the database and other times there may not be.

I have tried to look at doing the following after it runs and assign a value to it.

if (striko4goodproduct.Equals(null))
{

}

Upvotes: 2

Views: 14225

Answers (3)

Kobi
Kobi

Reputation: 138037

I think you are looking for this:

int striko4goodProductCount = GoodProduct.AsEnumerable()
  .Where(r => r.Field<string>("MachineID") == "Striko 4")
  .Sum(r => (r.Field<int?>("VIngot") ?? 0) +
            (r.Field<int?>("Heads") ?? 0) + 
            (r.Field<int?>("Risers") ?? 0));
  • Filtering by MachineID and then grouping by it will result in a single group - not very useful.

  • + has precedence over ??, so your code doesn't mean what it seems to mean. I've added parentheses to fix that.

  • striko4goodProductCount should be of type int, and will be 0 when there are no values - that is the default of Sum:

    This method returns zero if source contains no elements.

Upvotes: 2

sloth
sloth

Reputation: 101072

You can use DefaultIfEmpty

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

So you're looking for something like (note that I removed the anonymous type):

var striko4goodproduct = (from myrow in GoodProduct.AsEnumerable()
                          ...).DefaultIfEmpty(0);

This way, if the inner query don't return a result, DefaultIfEmpty ensures that there's at least a single element (0).


Note that if (striko4goodproduct.Equals(null)) will not work. A linq query will never return null; it will at least return an empty collection.

Upvotes: 2

James
James

Reputation: 82096

The Enumeration yielded no results is a debugger message, it's not something you would see at runtime so I wouldn't really concern myself with that.

Just check if the query has returned any results

if (striko4goodproduct.Any())
{
    ...
}

Upvotes: 3

Related Questions