using if else with LINQ Where - linq

I want to generate dynamic query to check manage the where clause with number of parameters available...if some parameter is null i don't want to include it in the where clause
var test = from p in _db.test
where if(str1 != null){p.test == str} else i dnt wanna check p.test
I have around 14 parameters for the where clause
need help,
thanks

You can do it in steps:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}

In addition to #Fredrik's answer, you can also use the short-circuit rules when evaluating boolean expressions like so:
var test = from p in _db.test
where str1 == null || p.test == str1;
Edit If you have lots of strings to test, (str1, str2, etc...) then you can use the following, which will be translated to an SQL IN clause:
var strings = new List<string>();
if (str1 != null) strings.Add(str1);
if (str2 != null) strings.Add(str2);
if (str3 != null) strings.Add(str3);
...
var test = from p in _db.test
where strings.Contains(p.test);
It's even easier if your strings are already in a collection (which, if you've got 14 of them, I assume they would be...)

Consider param1 and param2 are the parameters. Your query should be as under:
string param1 = "Value1";
string param2 = "Value2";
var q = from bal in context.FxBalanceDetails
where (string.IsNullOrEmpty(param1) || bal.Column1 == param1)
&& (string.IsNullOrEmpty(param2) || bal.Column2 == param2)
select bal;
This will ensure that the where clause gets applied for the particular parameter only when it is not null.

var test =
from p in _db.test
where p.str1 != null ? p.str1 : ""
select p;

Do you check the strings against the same Field of the entity?
If so you can write something like:
var strings = new[] { "foo", "bar", "ok", "", null };
var query = dataContext.YourTable.AsQueryable();
query = strings.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.Aggregate(query, (q, s) => q.Where(e => e.YourField == s));
EDIT:
The previous solution is overcomplicated:
var strings = new[] { "foo", "bar", "ok", "", null }.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var query = dataContext.YourTable.Where(e => strings.Contains(e.YourField));

Related

query cannot be enumerated more than once

I want to do the following
var totalNoOfRows = result.First().TotalNumberOfCount;
And finally do something like that
bookssList.AddRange(retResult.Select(r => r.ToBook()));
where ToBook is extended method
but I always get The result of a query cannot be enumerated more than once.
if (result != null)
{
var totalNoOfRows = result.First().TotalNumberOfCount;
pagingContext.ItemsTotal = totalNoOfRows != null ? int.Parse(totalNoOfRows.ToString()) : 0;
var retResult = result.ToList();
// pagingContext.ItemsTotal = totalcount.Value != null ? int.Parse(totalcount.Value.ToString()) : 0;
bookssList.AddRange(retResult.Select(r => r.ToBook()));
}
Hard to guess what are you doing, and how these snippets relate to each other, but if you can enumerate a collection only once, then call ToArray first:
var resultCopy = result.ToArray();
//... any number of operations on resultCopy
Note that calling First also counts as enumerating. So you need to enumerate and copy the collection even before this.
Try changing the code to this, so you only enumerate result once:
var retResult = result.ToList();
var totalNoOfRows = retResult.First().TotalNumberOfCount; //You are now using LINQ on the list, not the query!
pagingContext.ItemsTotal = totalNoOfRows != null ? int.Parse(totalNoOfRows.ToString()) : 0;
// pagingContext.ItemsTotal = totalcount.Value != null ? int.Parse(totalcount.Value.ToString()) : 0;
Logger.LogInfo("Search Payments GetPaymentsWithCount stored procedure result not null and count=" + totalcount);
bookssList.AddRange(retResult.Select(r => r.ToBook()));

EF/Code First / Linq --- How to filter a query "loop" but using "OR" [duplicate]

This question already has answers here:
Dynamic where clause (OR) in Linq to Entities
(2 answers)
Closed 8 years ago.
Normally when we have a grid result with multiple possible filters we may use a logic similar to this one:
var query = db.Something;
if(isFilter1 != null)
query = query.Where(x=>x.Prop1 == isFilter1);
}
if(isFilter2 != null)
query = query.Where(x=>x.Prop2 == isFilter2);
}
.... etc...
var finalResult = query.ToList();
But now I would like to use this kind of logic but using "OR" and not only "AND".
A simple example of the "end result of the query" that I want to achive.
var finalResult = db.Something.Where(x =>
x.Prop1 == null &&
x.Prop2 != 0 &&
x.Prop3 == id &&
(x.Prop4 == "String1" || x.Prop4== "String2" || x.Prop4== "String3"));
You can use Contains method:
var list = new[] { "string1", "string2", "string3"};
var finalResult = db.Something.Where(x =>
x.Prop1 == null &&
x.Prop2 != 0 &&
x.Prop3 == id && list.Contains(x.Prop4));

Converting a Query to LINQ

How can I convert the following query in a Linq with Lambda ?
SELECT DISTINCT Registro, COUNT(Registro) as qnt
FROM XML_Relatorio
WHERE Arquivo = 'redenet.xml'
AND TipoErro <> 'Imovel Inserido'
AND TipoErro <> 'TI'
AND DataHora BETWEEN '01-01-2012' AND '02-01-2012'
GROUP BY Registro
ORDER BY Registro
I'm trying the following code, but I need some help to build the LINQ with Lambda
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI");
Supposing the DataHora field is of Date or DateTime type.
// parse the strings to datetime
var start = DateTime.Parse("01-01-2012");
var end = DateTime.Parse("02-01-2012");
IQueryable<XML_Relatorio> quantidadeErro = db.XML_Relatorios
.Where(a => a.Arquivo == "redenet.xml"
&& a.TipoErro != "Imovel Inserido"
&& a.TipoErro != "TI"
// and compare them...
&& a.DataHora > start && a.DataHora < end);

LINQ: Build a where clause at runtime to include ORs ( || )?

I need to build a where clause at runtime but I need to do an OR with the where clause. Is this possible?
Here is my code. Basically "filter" is a enum Bitwise, son hence filter could be equal to more than 1 of the following. Hence I need to build up the where clause.
If I execute the WHEREs separately then imagine if I do the Untested first, and it returns 0 records that means I can't execute a where on the Tested because its now 0 records.
I will put some pseudo-code below:
string myWhere = "";
if ((filter & Filters.Tested) == Filters.Tested)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Tested";
}
if ((filter & Filters.Untested) == Filters.Untested)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Untested";
}
if ((filter & Filters.Failed) == Filters.Failed)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Failed";
}
// dataApplications = a List of items that include Tested,Failed and Untested.
// dataApplication.Where ( myWhere) --- Confused here!
Is this possible?
I don't want to include lots of "IFs" because there are lots of combinations i.e. no filter, filter= tested Only, filter = Untested and Tested ... and lots more.
If you have this:
IEnumerable<MyType> res = from p in myquery select p;
You can define a
var conditions = new List<Func<MyType, bool>>();
conditions.Add(p => p.PropertyOne == 1);
conditions.Add(p => p.PropertyTwo == 2);
res = res.Where(p => conditions.Any(q => q(p)));
And now the trick to make Lists of Funcs of anonymous objects (and you can easily change it to "extract" the type of anonymous objects)
static List<Func<T, bool>> MakeList<T>(IEnumerable<T> elements)
{
return new List<Func<T, bool>>();
}
You call it by passing the result of a LINQ query. So
var res = from p in elements select new { Id = p.Id, Val = p.Value };
var conditions = MakeList(res);
var statusTexts = new List<string>(); // Add desired status texts
dataApplication.Where(item =>
statusTexts.Any(status => item.Status == status))
Use HashSet<> for statuses, then .Contains will be O(1) instead of usual O(n) for List<>:
var statuses = new HashSet<string>() {"a", "b", "c"};
var list = new[] {
new { Id = 1, status = "a"},
new { Id = 2, status = "b"},
new { Id = 3, status = "z"}
};
var filtered = list.Where(l => statuses.Contains(s => l.status == s));

LINQ Next Item in List

Taking a look at my question HERE, I now want to return the next recommendation object (after) the one that matches the criteria.
So say I found item 6 out of 10, I'd like the query to return item 7 instead.
Or is there a better way?
Here's my current best method:
MyList.SkipWhile(item => item.Name != "someName").Skip(1).FirstOrDefault()
An earlier answer uses Skip(1).Take(1) which works, but returns a list of one result. In my case (and perhaps the OP's case), we're looking for the actual item. So my code skips until it gets to the one we're looking for (a Where would return a subset so we wouldn't have access to the next item) then skips one more and then gets the item.
Try this one
NEXT Item
MyList.SkipWhile(x => x != value).Skip(1).FirstOrDefault();
PREVIOUS Item note:Reverse() will not work for LINQ to SQL
var MyList2 = MyList.ToList();
MyList2.Reverse();
MyList2.SkipWhile(x => x != value).Skip(1).FirstOrDefault();
Since you have a List<T> object you can use its FindIndex method instead of Where to get the index of the first matching item rather than the item itself:
int index = recommendations.FindIndex(rp =>
rp.Products.Any(p => p.Product.Code == "A")
&& rp.Products.Any(p => p.Product.Code == "B")
);
Once you have the index you can get the next item or previous item or whatever you want.
How about something like this:
public static class Extension
{
public static T Next<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
bool flag = false;
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (flag) return enumerator.Current;
if(predicate(enumerator.Current))
{
flag = true;
}
}
}
return default(T);
}
}
You could then call it like you would for Where
Products.Next(x => x.Whatever);
This should do it. I haven't constructed a test for it specifically.
var nextProducts = from item1 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
join item2 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
on item1.Index equals item2.Index - 1
where item1.Rec.Products.Any(p => p.Code == "A")
&& item1.Rec.Products.Any(p => p.Code == "B")
select item2.Rec;
If you needed both records, the select statement could be
select new { MatchingItem = item1.Rec, NextItem = item2.Rec };
But then you would have to do a grouping to account for a matching item being the last item in the list (there would not be a next item in that case).
var nextProducts = from item1 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
join item2 in recommendations.Select((rec, idx) => new { Rec = rec, Index = idx })
on item1.Index equals item2.Index - 1
into groupjoin
from i2 in groupjoin.DefaultIfEmpty ()
where item1.Rec.Products.Any(p => p.Code == "A")
&& item1.Rec.Products.Any(p => p.Code == "B")
select new { MatchingItem = item1.Rec, NextItem = i2 == null ? null : i2.Rec };
The code I did test was something similar with a list of strings.
List<string> list = new List<string>() { "a", "b", "c", "a", "d", "a", "e" };
var query = from item1 in list.Select((s, idx) => new { Item = s, Index = idx })
join item2 in list.Select((s, idx) => new { Item = s, Index = idx })
on item1.Index equals item2.Index - 1
where item1.Item == "a"
select item2.Item;
Which returns b, d, and e.
If you are sure that:
the item is unique in the list
the item is gotten from the same list
there is the next item
you can get the next item this way
myList[myList.IndexOf(item) + 1];
// or
myList.ElementAt(myList.IndexOf(item) + 1);
If you're not sure there is the next item you can use try + catch or:
myList.ElementAtOrDefault(myList.IndexOf(item) + 1);
Is item 7 a match to your Where clause? If so, use the Skip() and Take() extension methods:
var myProducts =
from rp in recommendations
where
cp.Products.Any(p => p.Product.Code == "A") &&
cp.Products.Any(p => p.Product.Code == "B")
select rp;
var nextProduct = myProducts.Skip(1).Take(1);

Resources