Борясь немного сегодня.
У меня есть следующий метод, который возвращает список продуктов.. прекрасный.
public static List<tblWeight> GetProductInfo(string memberid, string locationid, string basematerial, string source)
{
MyEntities getproductinfo = new MyEntities ();
return (from p in getproductinfo .tblWeights
where p.MemberId == memberid &&
p.LocationId == locationid &&
p.BaseMaterialName == basematerial &&
p.WeightStatus == source
select p)
.ToList();
Как я иду о слиянии нескольких операторов IF в где пункт?
Например, если бы basematerial ddl не затронут, но объект в источнике ddl выбран, результат возвратил бы все связанное с basematerial, но фильтрованный выбранным источником.
Это даже имеет смысл?!
Я даже не уверен, что проявляю корректный подход - простите мое незнание.
вы можете добавить их к вашему запросу о необходимости:
var r = (from p in getproductinfo .tblWeights
where p.MemberId == memberid &&
p.LocationId == locationid &&
p.WeightStatus == source
select p)
if (!String.IsNullOrEmpty(basematrial))
r = r.Where(p => p.BaseMaterialName == basematerial);
return r.ToList();
Рассмотрите возможность реализации этих методов расширения с именем WhereIf
.
Вы передаете ему два параметра: оператор, оцениваемый как логическое, и лямбда-функцию. Если выражение bool истинно, лямбда добавляется.
WhereIf на ExtensionMethod.net
Ваш запрос может выглядеть так:
return getproductinfo.tblWeights
.Where(w=> w.MemberId == memberid &&
w.LocationId == locationid)
.WhereIf(!string.IsNullOrEmpty(basematerial), w=>w.BaseMaterialName == basematerial)
.WhereIf(!string.IsNullOrEmpty(source), w=>w.WeightStatus == source)
.ToList();
Вот они, для IEnumerable
и IQueryable
. Это позволяет вам использовать .WhereIf ()
в LINQ To SQL, Entity Framework, Lists, Arrays и во всем остальном, что реализует эти 2 интерфейса.
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}