Access entity array by index c# - c#

I have a table that represents a matrix:
CustType DiscountGroup1 DiscountGroup2 DiscountGroup3
Wholesale 32 10 15
Retail 10 15 0
All my stock items have a corresponding discount group code 1, 2 or 3.
At the time of invoicing I want to lookup the discount the customer type gets on the item(s) being invoiced.
The table needs to be able to grow to include new customer types and new discount groups so nothing can be hardcoded.
I figured I would pull the data into an array so I could select the column by index but I am getting stumped by my entities being too intelligent...
var disc = (from d in context.CustDiscountGroups
where d.CustType == Wholesale
select d).ToArray();
I can only access the columns by name ie: disc[0].DiscountGroup1
if I try disc[0,1] I get an error saying wrong number of indices inside.
What am I missing? I feel like it is something ridiculously fundamental. My only other thought was naming the columns as 1, 2, 3 etc and building a sql select string where I can use a variable to denote a column name.
The database is in design stages as well so the table(s) can be remade in any way needed, I'm struggling to get my head wrapped round which way to approach the problem.

your entity CustDiscountGroups having properties CustType, DiscountGroup1, DiscountGroup2, DiscountGroup3 and your query return array of CustDiscountGroups so you cant access like [0,1] there is no 2D array
if you need to access first item you can get it as disc[0] then you can get any of properties of discount group by name of the property. like
disc[0].CustType, disc[0].DiscountGroup1, disc[0].DiscountGroup2, disc[0].DiscountGroup3
If you want to get array of array then get the property value using reflection as below
var disc = context.CustDiscountGroups.Where(c=>c.CustType == Wholesale)
.Select(v=>typeof(CustDiscountGroups)
.GetFields(System.Reflection.BindingFlags.Public)
.Select(f=>f.GetValue(v)).ToArray())
.ToArray();
var disc = context.CustDiscountGroups.Where(c=>c.CustType == Wholesale)
.Select(v=>typeof(CustDiscountGroups)
.GetProperties()
.Select(f=>f.GetValue(v,null)).ToArray()).ToArray();
now you can access values like disc[0][1]
Please note: I haven't compiled and tested above code, please get the idea and change as you want

Related

Is it possible two compare two fields in same IEnumerable using Linq?

In researching this question, I found numerous answers for comparing two different lists. That is not my scenario. I have an IEnumerable of a class with several fields, and I need to filter where one field is greater than another field in the same list.
I can envision many uses for that type of comparison, but I am keeping things very simple in this example.
To give you a better context, here's a simple table made in T-SQL.
T-SQL code:
create table #GetMia1ASummaryBar (
Id int not null identity(1,1),
ShrCreditRate Float null,
NonShrCreditRate Float null
);
insert into #GetMia1ASummaryBar(ShrCreditRate,NonShrCreditRate)
values (null,1.5),(2.5,0.75),(2,2),(1,null);
-- to see the entire table
select * from #GetMia1ASummaryBar;
-- to filter where the first field is greater than the second
select * from #GetMia1ASummaryBar t where t.ShrCreditRate>t.NonShrCreditRate;
drop table #GetMia1ASummaryBar;
Using Linq, I would like to be able to do what I can do very easily in T-SQL: select * from #GetMia1ASummaryBar t where t.ShrCreditRate>t.NonShrCreditRate;
Along those lines, I tried this.
// select where first field is greater than second field
var list = repo.GetMia1ASummaryBar(campus)
.Where(l => l.ShrCreditRate > l.NonShrCreditRate);
While I received no compile errors, I received no records where I should have received at least one.
So instead of this,
Id ShrCreditRate NonShrCreditRate
----------- ---------------------- ----------------------
1 NULL 1.5
2 2.5 0.75
3 2 2
4 1 NULL
I'd like to filter to receive this.
Id ShrCreditRate NonShrCreditRate
----------- ---------------------- ----------------------
2 2.5 0.75
I'm really trying to avoid creating a separate list populated by a for-each loop, which would be a last resort. Is there a simple way to the type of Linq comparison I am trying to make.
Thanks to everyone who contributed in the comments. The short story is that this syntax is indeed valid.
// select where first field is greater than second field
var list = repo.GetMia1ASummaryBar(campus)
.Where(l => l.ShrCreditRate > l.NonShrCreditRate);
The reason the list was empty was because of an underlying dependency with a filter on it. I uncovered this unexpected behavior in an integration test, which once more shows the value of an integration test. (My unit test didn't uncover the unexpected behavior.)

Linq query for ordering by ascending order except for one row

I am pulling data from a table like the example below:
status_id status_description
1 Unknown
2 Personal
3 Terminated
4 Relocated
6 Other
7 LOP
8 Continuing
I want to get the results into a IEnumerable which i am then returning to the front end to display the descriptions in a dropdown.
I want to sort this alphabetically and have the "Other" option always show up in the bottom of the dropdown.
Is there any way to get this in the backend? Currently I have this:
IEnumerable<employee_map> map= await(from emp in db.emp_status_map
orderby emp.status_description
select emp).ToListAsync();
Simply order on two values, first on whether the description is Other, then on the actual description itself:
orderby emp.status_description == "Other", emp.status_description
Servy's answer is fine, it works and fullfils your requirements. Another solution slightly different would be to add a field called "DisplayOrder", for example, and set it to 1 for all the rows except for "other", and set it to 2 (or whatever number you want) to "other". Then, you just order by DisplayOrder, Description.
It's highly probably that this solution is gonna be much faster if you define an index on DisplayOrder, Description.

Compare List of Integers and add/remove the rows in database using the difference in result LinqtoSQL

Currently I'm working on a project using LinqtoSql and I would like to get an simpler solution for my current problem.
Example:
Lets say I got a table named Example with three rows (with values 1,2,4)
Now in code(c#) I got these values as a list of Integer(lets name it lstExisting)
Now in my method I got another List of Integer ( say lstCurrent) with Integers values (1,2,3)
Now I want to compare the both the list and find the difference of integers and update the database, so according to my example a new row with value 3 should be added and the existing row with value 4 should be deleted.
PS:(the integer values will be always unique and will be 1,2,3,4)
Linq solutions will be preferable but I don't mind other easier solutions.
Thanks
You need to find new items and to be deleted items using Except like:
var newItems = lstCurrent.Except(lstExisting).ToList();
var toBeDeletedItems = lstExisting.Except(lstCurrent).ToList();
Later you can iterate each list and Add/Delete accordingly.
Try using Contains(). With having two lists, you can write something like this. What this does is it iterates over each item in your methods list and checks the original to see if its there.
var lstExisting = getExistingList();
var lstCurrent = getCurrentList();
foreach(var currentInt in lstCurrent)
{
if(!lstExisting.Contains(currentInt))
{
//insert currentInt
}

How to validate every value in a List in where Clause?

The Title is a little bit complicating.
The Question here is easy:
If got a CheckBoxList. In this List you are allowed to do multiple choice. I put every chosen value from the Checkboxlist into a list because i need it for my where clause. So i have:
List<int> queueIDList = new List<int>();
Short version of my LINQ:
var reports = from t in tickets
where t.queue_id == every value in queueIDList
select t.ticketnumber;
So how do i have to write it when i want every ticketnumber from DB which is the same like in the queueIDList?
For better knowing - in the CheckBoxList u can chose different Queues, at least u have to chose 1 (null is not allowed). I added the ID's of the chosen Queues to a list and now i want to have every ticketnumber from DB where the queueID equals with the values from the queueIDList.
I think the answer is easy but i'm really stuck with my mind.
Thanks for every help!
You can just use Contains:
var reports = from t in tickets
where queueIDList.Contains(t.queue_id)
select t.ticketnumber;

How do I identify unique properties of elements within my array?

Let's say I work at the Dept. of Health. I've processed food poisoning complaints and stored the complaints data into a multi-dimensional array like so:
ID - 5 digit ID number for the restaurant victim ate at
Date - Date of Food Poisoning
Name - Name of Victim
Age - Age of Victim
Phone - Victim's Phone Number
Array[0] contains the first complaint's data. Array[0].ID contains the restaurant ID of the first complaint and so forth.
Within my array how do I extract a list of unique 5 digit IDs?
Some restaurants might have 50 complaints and some might have just 1. I want to create a list of all of the unique restaurant IDs that show up in my complaints data.
var Unique = array.ID.Distinct();
does not work. What am I doing wrong?
Select() first...
var ids = array.Select(o => o.ID).Distinct();
Edit:
Hi, can you please explain why.
First, let's talk about what you did wrong:
var ids = array.ID.Distinct();
You tried to refer to ID, a non-existent member of the array. What you're looking for is the ID of an item within the array.
You tried to call Distinct() on that non-existent member rather than the collection.
Now let's look at what the new code does:
var ids = array.Select(o => o.ID).Distinct();
That Select() generates a new enumerable yielding only the ID values. The Distinct() generates another enumerable, yielding only the unique values from the Select().
Use a HashSet if you plan to do lookups going forward:
var hashSet = new HashSet<int>(array.Select(i => i.ID));
This will automatically remove duplicates and also allow near O(1) lookups.

Categories

Resources