Modify IList Query Statement - c#

I have the following statement, and I want to modify it to not select all tables.
Exclude 2 columns customerItemNo and manufacturerItemNo in the if, and
Exclude 2 columns customerItemNoAppend and manufacturerItemNoAppend in the else if.
How can I do it?
if (p.UserInternal == 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location);
else if (p.UserInternal != 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location && (r.CustomerID == customerID || r.CustomerID == " "));
else
inventorySummary = new List<Q_TBL_INVENTORY_SUMMARY>();

Related

To convert if condition to linq in cshtml

Code
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
}
}
I have tried the following code and unable to complete it fully as expected
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where((a => a.CurrentStatus == 1 || a.CurrentStatus == 2)
&& )
})
How to convert the above if condition to linq in cshtml. Thanks
the else-if relationship is an OR relationship. So simply combine the two lines. the inner nested if inside the else if is an AND relationship. This would go into the second set of parentheses
Collection = Model.Collection.Where
(
(a => a.CurrentStatus == 1 || a.CurrentStatus == 2) ||
((a.CurrentStatus == 3 || a.CurrentStatus == 4) && a.Date != null && a.Date <= 30)
)
EDIT:
Here is another suggestion: extract the readable code into an own method that evaluates the condition and returns the boolean result. This way you can make a predicate that can be accepted by the Where method:
private bool IsForDisplay( ModelDataType Model )
{
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
return true;
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
return true;
}
}
return false;
}
now you can use it simply in the linq expression:
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where(a => IsForDisplay(a))
});

Store math operator in variable

I am creating an application in C# MVVM. I have a simple question. Is there any possibility to store math operator in variable? I have a code like that:
public ICollectionView FilteredCollection
{
get
{
return filteredCollection;
}
set
{
filteredCollection = value;
OnPropertyChanged("FilteredCollection");
}
}
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary == Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
);
What I want to achieve:
In fourth line (DynamicSearchEmployeeSalary) math operator should be depended on following conditions:
if (IsPressedEqual == true)
VARIABLE = "=="
if (IsPressedLess == true)
VARIABLE = "<"
if (IsPressedGreater == true)
VARIABLE = ">"
if (IsPressedLess == true && IsPressedEqual == true)
VARIABLE = "<="
if (IsPressedGreater == true && IsPressedEqual == true)
VARIABLE = ">="
Scenario:
For example I put a value like 10000 in textbox, then click on button with "=" operator. As a result I want to receive Employees with Salary equals than 10000.
Then I click on ">". And I have Employees with Salary greater and equals 10000.
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary VARIABLE Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
I've made a simple Rule Based Engine ... I think it will help you in your issue ...
please find it as a nuget package here: https://www.nuget.org/packages/IbnSherien.RuleBasedEngine/
you can create a rule like this:
var rule = RuleEngine.CreateRule<Employee>()
.If<Employee>(e => e.EmployeeSalary).GreaterThan(DynamicSearchEmployeeSalary)
.Validate();
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || rule.Match((Employee)x).IsMatch)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
feel free to add any comments or contribute to the package

Linq To Entities: Checking Multiple Columns Against against a Set of Values

I have a MySQL DB that I'm trying to query with the Entity Framework.
I have a Match table that looks like this:
match_id, winning_hero1, winning_hero2, winning_hero3, winning_hero4, winning_hero5
with a winning_hero being identified by an integer.
given a list of hero ids, I want to return all matches where these heroes were all on the winning team together.
something like this:
public List<MatchEntity> GetAllMatchesWithWinningHeroes(List<int> heroList)
{
List<MatchEntity> matchList = null;
using (var context = new dotaEntities())
{
switch (heroList.Count)
{
case 1:
matchList = context.MatchEntities.Where(m => m.winning_hero1 == heroList[0]
|| m.winning_hero2 == heroList[0]
|| m.winning_hero3 == heroList[0]
|| m.winning_hero4 == heroList[0]
|| m.winning_hero5 == heroList[0]).ToList();
break;
case 2:
matchList = context.MatchEntities.Where(m => (m.winning_hero1 == heroList[0]
|| m.winning_hero2 == heroList[0]
|| m.winning_hero3 == heroList[0]
|| m.winning_hero4 == heroList[0]
|| m.winning_hero5 == heroList[0])
&& (m.winning_hero1 == heroList[1]
|| m.winning_hero2 == heroList[1]
|| m.winning_hero3 == heroList[1]
|| m.winning_hero4 == heroList[1]
|| m.winning_hero5 == heroList[1])).ToList();
break;
case 3:
//etc..
}
return matchList;
}
}
Is there a "nicer" way to go about selecting these matches?
Thank you.
What you need is this:
using (var context = new dotaEntities())
{
var matchList = context.MatchEntities.Where(m =>
heroList.Contains(m.winning_hero1) &&
heroList.Contains(m.winning_hero2) &&
heroList.Contains(m.winning_hero3) &&
heroList.Contains(m.winning_hero4) &&
heroList.Contains(m.winning_hero5)).ToList();
}
But, your data design is wrong. In your Match table, you should only have a MatchID (PK), and probably MatchName or MatchDate, and in your Hero table, you should have HeroID (PK), HeroName,... Then, you should have a third table (MatchHero) just to create a many-to-many relationship between the two tables. In your MatchHero table, you'll have MatchID and HeroID.
I think this is what you want:
using (var context = new dotaEntities())
{
matchList = context.MatchEntities.Where(m=>
( heroList.Contains(m.winning_hero1)?1:0 +
heroList.Contains(m.winning_hero2)?1:0 +
heroList.Contains(m.winning_hero3)?1:0 +
heroList.Contains(m.winning_hero4)?1:0 +
heroList.Contains(m.winning_hero5)?1:0
) == heroList.Count
).ToList();
}
This assumes that all winning_heros are different.

Using Thread.Start() on a method that takes parameters and returns values

I call a particular function on multiple threads as follows:
int q = 0;
for (int j = 0; j < number; j++)
{
int copy = q;
int copy1 = j;
if (!display_status[copy1].Equals("NO") && (selection == "ALL" || (selection == "ALL-LAE" && license[copy1] != "") || (selection == "ALL-NON LAE" && license[copy1] == "") || (selection == "AVIONICS -ALL" && trade[copy1] == "Avionics") || (selection == "AVIONICS-NON LAE" && trade[copy1] == "Avionics" && license[copy1] == "") || (selection == "AVIONICS-LAE" && trade[copy1] == "Avionics" && license[copy1] != "") || (selection == "AIRFRAME-ALL" && trade[copy1] == "Airframes") || (selection == "AIRFRAME-NON LAE" && trade[j] == "Airframes" && license[j] == "") || (selection == "AIRFRAME-LAE" && trade[j] == "Airframes" && license[j] != "")))
{
int numberofprojects = numberc;
string[] nameofproj = listc[0].ToArray();
string[] name = list[0].ToArray();//list of manpower names
string man_name = name[copy1];//Name of manpower
List<string>[] lista = new List<string>[5];
string[] status = listc[13].ToArray();
thread[copy] = new Thread(() => {new_value[copy]=graph1threader(man_name,numberofprojects, nameofproj, status);});
thread[copy].Start();
q++;
}
}
graphthreader1() does not seem to be returning any value, as all elements of new_value hold the value 0 even after the function is called. What may be the reason? Is there a simple solution for this problem?
The most likely cause is that graph1threader has not finished yet, one way you can workaround this is by calling thread[copy].Join() but most likely this will defeat the purpose of using threads at all, another way will be by joining the first thread only at the end of the loop, but it depends on what you want to achieve with your code.

LINQ Method Syntax - how to accomplish dynamic Linq statements

I use Linq to Entities to retrieve my records from DB. The function below is in a method. Method has some parameters (arguments) like group, datefrom, dateto, place, state , searchtext etc. etc.
the whole idea is if these parameters are not empty or null then accomplish the LINQ statments. The way I'm doing is I'm checking whether there is a value or not. if it has the value then I pass e.g. a.no_group= group if it doesn't has a value then I pass a statement like a.id!=-1, which is always true.
Problem:
I mean I'm not happy with passing in every statement like "a.id != -1" which is always true . I use this because I have to put a value there. But I'm not happy with this way of doing it... (it works!)
Question:
The question is: this right way of doing?
1- Can I replace a.id != -1 with something else ?
2- If you see the whole linq statement is duplicated because of language check. As you see the last
linq statement checks on language 'Dutch' or 'French'... How to avoid dupliation?
3- I'm checking whether the current date (datetime.now) is between date_begin and date_end. Is this correct way...
The whole code works fine, but I think I'm complicating the code which can be much simpler...
But how?
if (Language == ConfBouwHelper.LanguageEnum.French)
{
//FRENCH RECORDS
listAgendaItems = dc.agenda.Where(a =>
((String.IsNullOrEmpty(group)) ? (a.id != -1) : (a.no_group == group))
&& ((activityType.Equals("ALL")) ? (a.id != -1) : (a.type_manifestation == activityType))
&& ((String.IsNullOrEmpty(dateFrom)) ? (a.id != -1) : (a.date_debut.Value >= dateFrom))
&& ((String.IsNullOrEmpty(dateTo)) ? (a.id != -1) : (a.date_debut.Value <= dateTo))
&& ((String.IsNullOrEmpty(place)) ? (a.id != -1) : (a.emplacement.Contains(place)))
&& ((String.IsNullOrEmpty(state)) ? (a.id != -1) : (a.cd_prov == state))
&& ((String.IsNullOrEmpty(searchText)) ? (a.id != -1) : (a.libelle_activite.Contains(searchText)))
&& ((a.date_begin_display.HasValue ? DateTime.Now >= a.date_begin_display.Value : a.id != -1) &&
(a.date_end_display.HasValue ? DateTime.Now <= a.date_end_display.Value : a.id != -1))
&& (a.langue == "FRENCH" || a.langue == "B")).ToList<agenda>(); //GET FRENCH
}
else
//DUTCH RECORDS
{
listAgendaItems = dc.agenda.Where(a =>
((String.IsNullOrEmpty(group)) ? (a.id != -1) : (a.no_group == group))
&& ((activityType.Equals("ALL")) ? (a.id != -1) : (a.type_manifestation == activityType))
&& ((String.IsNullOrEmpty(dateFrom)) ? (a.id != -1) : (a.date_debut.Value >= dateFrom))
&& ((String.IsNullOrEmpty(dateTo)) ? (a.id != -1) : (a.date_debut.Value <= dateTo))
&& ((String.IsNullOrEmpty(place)) ? (a.id != -1) : (a.emplacement.Contains(place)))
&& ((String.IsNullOrEmpty(state)) ? (a.id != -1) : (a.cd_prov == state))
&& ((String.IsNullOrEmpty(searchText)) ? (a.id != -1) : (a.libelle_activite.Contains(searchText)))
&& ((a.date_begin_display.HasValue ? DateTime.Now >= a.date_begin_display.Value : a.id != -1) &&
(a.date_end_display.HasValue ? DateTime.Now <= a.date_end_display.Value : a.id != -1))
&& (a.langue == "DUTCH" || a.langue == "B")).ToList<agenda>(); //GET DUTCH
}
You can add multiple where clauses:
var query = dc.agenda;
if(!String.IsNullOrEmpty(group))
query = query.Where(a => a.no_group == group)
if(!activityType.Equals("ALL"))
query = query.Where(a => a.type_manifestation == activityType)
// and so on for all your conditions...
if (Language == ConfBouwHelper.LanguageEnum.French)
query = query.Where(a => (a.langue == "FRENCH" || a.langue == "B"));
else
query = query.Where(a => (a.langue == "DUTCH" || a.langue == "B"));
listAgendaItems = query.ToList<agenda>();
This is a lot cleaner and readable and also solves the problem with the duplication because of the languages.

Categories