Reputation: 11304
In the below C# code, I am doing 2 iterations over data
and trying to create a filter that looks like this,
(Name1 = 'd1' AND Name2 = 'd1') OR (Name1 = 'd3' AND Name2 = 'd3') OR (Name1 != 'd1' AND Name1 != 'd3')
For the below sets of data:
var data = new List<(string, string)>
{
("d1", "d2"), ("d3", "d4"),
};
Here is code:
foreach(var entity in data)
{
filter += $"(Name1 = '{entity.Item1}' AND Name2 = '{entity.Item1}') OR ";
}
filter = filter + "(";
foreach (var entity in data)
{
filter += $"Name1 != '{entity.Item1}' AND ";
}
//remove last "AND"
var final = filter.Substring(0, filter.LastIndexOf("AND")).TrimEnd() + ")";
How I can improve this code and get rid of 2 iterations? Thanks.
Upvotes: 1
Views: 103
Reputation: 7186
Use Linq and string.Join
to iterate once and avoid SubString
:
var data = new List<(string, string)> { ("d1", "d2"), ("d3", "d4"), };
var exclude = new List<string>();
var filters = string.Join(" OR ", data.Select(entity => {
exclude.Add($"Name1 != '{entity.Item1}'");
return $"(Name1 = '{entity.Item1}' AND Name2 = '{entity.Item1}')";
}));
string final = $"{filters} OR ({string.Join(" AND ", exclude)})";
Upvotes: 2
Reputation: 61839
You can have two filter strings which you build up simultaneously and then combine at the end:
string filter = "";
string filter2 = "";
var data = new List<(string, string)>
{
("d1", "d2"), ("d3", "d4"),
};
foreach(var entity in data)
{
filter += $"(Name1 = '{entity.Item1}' AND Name2 = '{entity.Item1}') OR ";
filter2 += $"Name1 != '{entity.Item1}' AND ";
}
filter2 = filter2.Substring(0, filter2.LastIndexOf("AND")).TrimEnd();
string final = $"{filter}({filter2})";
Live demo: https://dotnetfiddle.net/TGr6Jz
Upvotes: 2