How to compare linq query result against textbox.value - c#

I have the following linq query:
var solicitudes = from s in dbContext.Menores
select s.Solicitud.fiExpEmpleado;
The query results are 41 employees' Ids. My question is, how can I compare these 41 elements against the value of a textbox so that i can restrict user registration (if the ID of the textbox matches with one of the query result the registration is denied)?
Hope your help.

You can write a query that checks whether the value exists:
if (dbContext.Menores.Any(s => s.Solicitud.fiExpEmpleado == someValue))

string text = textbox.Text.Trim();
var solicitudes = (from s in dbContext.Menores
where s.FieldToCheck == text
select s.Solicitud.fiExpEmpleado).FirstOrDefault();
if (solicitudes != null)
{
//Deny
}

If solicitudes is being returned as a list of ints you could just to:
int employeeId = Convert.ToInt32(txtMyTextBox.Text);
bool isValidEmployeeId = solicitudes.Any(employeeId);

You don't have to compare all values, just create linq query which query for the value of the textbox, and then count use count method,if count is greater then zero, it means it exits,and you can then deny the user.

Here you go.
if (dbContext.Menores.Exists(x => x.FieldToCheck == text))
{
//deny
}

Related

how could i handle this linq query and compare it with and int in an if-statement?

i have the following code:
int selectedcourseId = Convert.ToInt32(c1.Text);
var cid = (from g in re.Sections where g.CourseID == selectedcourseId select g.CourseID);
int selectedinstructorid = Convert.ToInt32(c2.Text);
var iid = (from u in re.Sections where u.InstructorID == selectedinstructorid select u.InstructorID);
i want to compare the two (selectedcourseId) with (cid) and (selectedinstructorid) with (iid) in if-statement such as:
if (selectedcourseId = cid && selectedinstructorid = iid)
{
MessageBox.Show("it already exists");
}
i have tried many things that didnt work our because i have limited knowledge.
thank you very much in advance for any comment or answer
You can change your code as: (but it is meaningless for your situation to check this)
if (selectedcourseId == cid.First() && selectedinstructorid == iid.First())
First of all for checking equality in if statement you must use ==, not =. And the second is the IQueryable<T> allows you to execute a query against a specific data source, but it uses deferred execution. For executing it in your case, you can use First().
But, I suggest that you are just learning how to use LINQ and therefore you have written this code.
I don't know what you are trying to achive. But, if you want to search if there is any result with that ID's, the you must use Any():
var result1 = from g in re.Sections where g.CourseID == selectedcourseId select g.CourseID;
var result2 = from u in re.Sections where u.InstructorID == selectedinstructorid select u.InstructorID;
if(result1.Any() && result2.Any()) { ... }
Or, if you want to find if there is any row which has specified CourseID and InstructorID, then you can call one Any():
if(re.Sections.Any(x => x.CourseID == selectedcourseId && x.InstructorID == selectedinstructorid))
{ ... }
Let me try to find the X from this XY-problem. I guess you want to check if there is already a combination of courseid + instructorid. Then use a single query:
var data = from section in re.Sections
where section.InstructorID == selectedinstructorid
&& section.CourseID == selectedcourseId
select section;
if(data.Any())
{
MessageBox.Show("it already exists");
}
You should not do it in two queries, because the two results might be related to two different rows. This would lead to "false positives" when an instructor handles some section, and a course has some instructors, but the two matches do not belong to the same row:
course instructor
------ ----------
100 10
101 15
102 20
If you are looking for a combination (101, 10) it is not enough to see that 100 is present and 10 is present; you need to check that the two belong to the same row in order to consider it a duplicate.
You can fix this by making a "check presence" query, like this:
var existing = re.Sections
.Any(s => s.InstructorID == selectedinstructorid && s.CourseID == selectedcourseId);
if (existing) {
MessageBox.Show("it already exists");
}
if (selectedcourseId = cid && selectedinstructorid = iid)
this will not work, since single '=' is an assignment, not a comparation (which is '==')
also, you can try to do something like this
var cid = (int)((from g in re.Sections where g.CourseID == selectedcourseId select g.CourseID).FirstOrDefault());
so you select the first or default record from your list and cast it to int

linq difference between two select count queries

I'm trying to learn about linq queries. I have a list _taskDetail which contains 8 elements. I do not understand why the first query below returns the answer 8? Yes the list contains 8 elements but all the td.Names are different and I have specified td.Name == taskName so why is it returning everything even elements where the td.Name does not equal taskName?
The second query gives me the expected and correct answer of 1.
var Ans1 = _taskDetail.Select(td => td.Name == taskName).Count();
var Ans2 = (from tdList in _taskDetail
where tdList.Name == taskName
select tdList).Count();
Ans1 = 8
Ans2 = 1
The first version doesn't make sense, you need a Where, and not a Select which is a projection, not a filter.
The Select, in the first version, will return you an IEnumerable<bool> (for each item in the list, it will return true if Name == taskName and false if not. So all items will be returned, and the count will give you... the count of the list.
so
_taskDetail.Where(td => td.Name == taskName).Count();
By the way, you can simply do
_taskDetail.Count(td => td.Name == taskName);
Detail to maybe understand better
The second (wrong) version (query syntax) corresponding to your actual (wrong) first version (method syntax) would be
(from tdList in _taskDetail
select tdList.Name == taskName).Count();
It's because the first query is wrong. Select only produces a projection, it does NOT filter the results. The correct way to execute is using Where instead of Select...
var Ans1 = _taskDetail.Where(td => td.Name == taskName).Count();

C# Linq Select Rows Where ID Equals ID in CSV

What I have is a string of comma separated IDs that I'm receiving from a query string (e.g. 23,51,6,87,29). Alternately, that string could just say "all".
In my Linq query I need a way to say (in pseudo code):
from l in List<>
where l.Id = all_of_the_ids_in_csv
&& other conditions
select new {...}
I'm just not sure how to go about doing that. I'm not even sure what to google to get me going in the right direction. Any pointing in the right direction would be extremely helpful.
I would suggest to split your query in 2 - first part will select by ID, and the select one will select other conditions.
First of all: check if query string contains numbers, or is just all:
var IEnumerable<ListItemType> query = sourceList;
if(queryStringValue != "All")
{
var ids = queryStringValue.Split(new[] { ',' })
.Select(x => int.Parse(x)) // remove that line id item.Id is a string
.ToArray();
query = query.Where(item => ids.Contains(item.Id));
}
from l in query
// other conditions
select new {...}
Because LINQ queries have deffered execution you can build queries like that without performance drawback. Query won't be executed until you ask for results (by ToList call or enumeration).
If you really want it with just one LINQ query:
var idArray = all_of_the_ids_in_csv.Split(',');
from l in List<>
where (all_of_the_ids_in_csv == "All" || idArray.Contains(l.Id))
&& other conditions
select new {...}
The trick is using string.Split
var ids = string.split(rawIdString, ",").ToList();
var objects = ids.Where(id=> /*filter id here */).Select(id=>new { /* id will be the single id from the csv */ });
// at this point objects will be an IEnumerable<T> where T is whatever type you created in the new statement above

validate search result using Linq

I have a search result from the database,
int searchTerm = "xx"
var result = from orderLines in context.OrderLineSearch(searchTerm)
select new
{
OrderNumber = orders.OrderNumber,
OrderLineId = orders.OrderLineId
};
I need to validate whether result contains many orders. That is I need to check whether multiple orders are returned or not.
I did the validation by storing the first order number in a variable and compared whether all the other rows contains only this order number. See below
string orderNumber = result.First().OrderNumber;
bool isValid = result.Where(x => x.OrderNumber != orderNumber).Count() == 0;
I want to know the best way to validate using LINQ? Can any one help me?
Thanks in advance.
May be you should to try group results by OrderNumber and then calculate Count?
var result = from orderLines in context.OrderLineSearch(searchTerm)
group orderLines by orderLines.OrderNumber into g
select g.Key
bool hasElements = result.Any();

How to improve this LINQ query for search

Can I improve this LINQ query
var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text.ToLower())
|| Dep.DepNm.StartsWith(txt1.Text.ToUpper())
||Dep.DepNm.Contains(txt1.Text))
select Dep;
Currently, you do a .Text, .Text.ToUpper() and .Text.ToLower() of the fixed value per item; (the ToUpper() etc being relatively expensive); you can lift this out:
string text = txt1.Text, upper = text.ToUpper(), lower = text.ToLower();
var filter = from Dep in deptlist
where Dep.DepNm.StartsWith(lower) || Dep.DepNm.StartsWith(upper)
|| Dep.DepNm.Contains(text))
select Dep;
I'm assuming here that .DepNm is trivially cheap. If this is actually an expensive property to query, you can use let to minimise the calls:
var filter = from Dep in deptlist
let name = Dep.DepNm
where name.StartsWith(lower) || name.StartsWith(upper)
|| name.Contains(text))
select Dep;
var filter = from Dep in deptlist
where Dep.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper()))
select Dep;
If it's possible in your solution, add lambda expressions. So you saved at least one line :)
EDIT:
Forget what I was saying, this is MUCH shorter:
var filter = deptlist.where(d => d.DepNm.ToUpper().Conatins(txt1.Text.ToUpper())).ToList();
I think it's faster because there is less conditions.
var filter = from Dep in deptlist
where (Dep.DepNm.StartsWith(txt1.Text, StringComparison.OrdinalIgnoreCase))
||Dep.where(d => d.DepNm.ToUpper().Contains(txt1.Text.ToUpper()))
select Dep;
answer is good , i refer viewing this link that relation with search and improvement use query linq in search with empty field
this is multiple choice for filling or not filling textbox, but this answer is work when :
you are one field filling or two field filling or .. 7th field filling .

Categories

Resources