Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq check for null and replace null value in orderby

Tags:

c#

linq

I have a linq query where sometimes the string field, product name, may be empty, null. This is a new field in the table and if data hasn't been entered, then I get an error when running the query. What I need to do is check for null and if null replace the null/empty value with the text value from a drop down list. I've tried several things but can't get it to work.

public IQueryable<Product> BindProduct([Control("ddProductName")] int? ProductNameId)
{
   var prod = from c in _DbContext.Products
      where c.ProductNameId == ProductNameId
      orderby string.IsNullOrEmpty(c.ProductName) ? ddProductName.SelectedItem.Text : c.ProductName,
      c.ItemNumber
      select c;
      return prod;
}

CHANGED TO:

 public IQueryable<Product> BindProduct([Control("ddProductName")] int? ProductNameId)
    {
        var prodName = ddProductName.SelectedItem.Text;
        var prod = from c in _DbContext.Products
                   where c.ProductNameId == ProductNameId
                   let sortName = c.Name ?? prodName
                   orderby sortName, c.ItemNumber
                   select new { c, sortName };
        return prod;

    }

UPDATE: I don't think I was clear. What I need to do is check for null and if null replace the null/empty value with the text value from a drop down list.

like image 674
Sheri Trager Avatar asked Dec 25 '22 19:12

Sheri Trager


2 Answers

"Let" keyword should do the trick.

Here is a LINQPad example:

var products = Enumerable.Range(0, 100).Select(q => new {ProductNameId = 1, ProductName = (q % 15 == 0 ? null : (q % 3 == 0 ? "Fizz" : (q % 5 == 0 ? "Buzz": q.ToString()))), ItemNumber = q});
var ddProductName_SelectedItem_Text = "FizzBuzz";
var ProductNameId = 1;
var prod = from c in products
                     where c.ProductNameId == ProductNameId
                     let sortName = c.ProductName ?? ddProductName_SelectedItem_Text
                     orderby sortName, c.ItemNumber
                     select c;
return prod; //prod.Dump(); //for linqpad debugging
like image 68
Valera Kolupaev Avatar answered Dec 28 '22 09:12

Valera Kolupaev


The answer came from a peer of mine, Brad. For anyone else who is wondering how to replace a null/empty value using linq, see below.

public IQueryable<Product> BindProduct([Control("ddProductName")] int? ProductNameId)
{
    var prodName = ddProductName.SelectedItem.Text;
    var prod = _DbContext.Products.Where(c => c.ProductNameId == ProductNameId).ToList().Select
    (p =>
    {
        p.Name = string.IsNullOrEmpty(p.Name) ? prodName : p.Name;
        return p;
    }).OrderBy(p => p.Name).ThenBy(p => p.ItemNumber).AsQueryable();

    return prod;
}
like image 37
Sheri Trager Avatar answered Dec 28 '22 10:12

Sheri Trager