user7676403
user7676403

Reputation:

How to assign "var" inside if statement

I need to do this:

var productsLocation = response.blah blah; //with linq query
var item; // even var item = null; //not valid
if(condition){
    item = productsLocation.linq query
} else {
    item = productsLocation.differentquery
}
var group = item.query;

Is this possible? If yes, how?

EDIT: here is my exact code:

var productLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
var items;
if (condition)
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
} else {
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));                        
}

Upvotes: 0

Views: 199

Answers (3)

Dax Fohl
Dax Fohl

Reputation: 10781

If you look closely at the logic, you notice you don't actually even need the if block. The whole thing can be written in one expression as follows:

var items = productLocation
  .Select(s => new ProductClass(s))
  .Where(s => categories.Contains(s.CategoryName) && (condition || stocks.Contains(s.Barcode)));

Upvotes: 1

kgzdev
kgzdev

Reputation: 2885

First of all get your response variable type, then initialize 'item' variable as IEnumarable where T is same as response variable type

var productsLocation = response.productLocation.Select(p => ProductLocationStaticClass.DtoToModel(p));
IEnumerable<ProductClass> item;  
if (condition)
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName));
} 
else 
{
    items = productLocation.Select(s => new ProductClass(s)).Where(s => categories.Contains(s.CategoryName) && stocks.Contains(s.Barcode));             
}
var group = item.Where(condition);

Upvotes: 0

Samvel Petrosov
Samvel Petrosov

Reputation: 7696

You can do it with IEnumerable interface in this way:

using System.Collections;
using System.Collections.Generic;

List<string> products = new List<string>() { "First", "Second", "Third", "Fourth" };
IEnumerable item;
var condition = false;
if (condition)
{
    item = products.Select(x=>x);
}
else
{
    item = products.Where(x => x.StartsWith("F"));
}
var group =  item.Cast<string>().Where(/*...Here your conditions...*/)

Upvotes: 0

Related Questions