C# – Linq check for null and replace null value in orderby

clinq

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.

Best Answer

"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