Send a cell from table to a variable - c#

I have a table like this:
table1(ID(int),total(int))
What I want to do is I want to send total value from table to a variable I made in C# using LINQ something like this:
int a;
a=table1.total();
Now I know this is wrong, pretty sure we have nothing of this sort in C# but I need something like that, because I wanna use this variable in another place. I have tried bringing it straight from table but it doesn't work at all.

ok so this is how i did it
DataClasses1DataContext db = new DataClasses1DataContext();
table1 b = (from r in db.table1
where row.id == 1
select r).FirstOrDefault();
int a;
a=convert.toint32(b.total);
that pretty much did what i wanted now the variable a has the value of total from table1 and i can use it on other parts of program
thank you for taking the time to look at my question.

Related

C# LINQ search by position

I'm trying to recreate the following SQL query in LINQ:
select * from table where column like 'RECORD_%01'
What I have is:
var data = from t in context.table
where t.column.StartsWith("RECORD")
&& t.column.EndsWith("01")
select t;
which is equivalent to:
select * from table where column like 'RECORD%01'
Can someone help me as to how I can add the condition for '_%', not '%'?
If you guys don't know what I'm talking about with the SQL issue, please check the following image, which explains SQL.
This is what you want (or something very similar):
https://learn.microsoft.com/en-us/dotnet/api/system.data.linq.sqlclient.sqlmethods.like
LINQ2SQL LIKE Command for Phrase
This allows you to specify a LIKE statement.
var data = from t in context.table
where SqlMethods.Like(t.column, "RECORD_%01")
select t;
From this it seems like you wanted to make sure that
It starts with RECORD
It ends with 01
And there is atleast one character after RECORD before 01
In this case you can check start with, end with and also the length.
var data = from t in context.table
where t.column.StartsWith("RECORD")
&& t.column.EndsWith("01")
&& t.column.Length>=9
select t;
Here's one way:
var data = from t in context.table
where t.column.StartsWith("RECORD")
&& t.column.EndsWith("01")
&& t.column.Length > 8
select t;
This makes sure that at there is at least one character between RECORD and 01.
Of course, depending on what Query Provider you're using, you may want to simply try use the LIKE operator using SqlMethods.Like, SqlFunctions.PatIndex or one of the methods describe here.

Simple math on SQL query results or on a datatable

Let's say I have a query that returns something simple like...
**TYPE** **TOTAL**
A 2
B 4
And I want to do some math like A/(A+B) -> 2/(2+4) then display that on my website. Is that more feasible to do within the query or after when I have it stored in a datatable??
Just try something like this if you realy need to get it done in same way.
SELECT A/(A+B) FROM((SELECT total as A FROM TB WHERE type='A' LIMIT 1),(SELECT total as B FROM TB WHERE type='B' LIMIT 1))
Tested and working..

Fastest way for querieng multiple queries

What i need to do is this:
I got an array with lets say 100000 values, For each value i need to make the same query ,just change that specific value.
Now, i am thinking that if i loop all this values in my c#/ java code and reach for a query it would take a lot of time.
My other option is doing all the work in my db, populate a temp table and than reading back in my code from that temp table.
What is the fastest way of doing such thing?
private void GetValues(List<Element> _Elements)
{
foreach (Element e in _Elements)
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = _conn;
cmd.CommandText = "select value from table where something = " +e.Indicator;
using(OracleDataReader r = cmd.ExecuteReader());
while (r.Read())
{
e.setvalue = r.GetString(1);
}
r.Close();
}
}
}
}
[Editor note: question was originally unclear as to whether it was C# or Java -- but the languages are largely equivalent, and answers should be applicable to both.]
Do one query,
select value from table where something between min and max;
or
select value from table where something in (a, b, c, ... );
or
select value from table where something in
(select things from tempTable);
or
select value from table where something in
(select things from #tablevariable);
whichever of these approaches is most applicable to your database and problem.
Repeating all the processing over and over, than amalgamating the results must be slower than taking a set based approach in the first place.
It all rather depends on on the type and distribution of the Indicator property of the Element List.
The faster way is to use a dynamic query. In a loop, you build up a statement to make use of several values at once.
In the sample you gave, it mean building up statements like those.
query1: select value from table where something in (n1, n2,... ,n500)
query2: select value from table where something in (n501, n502,... ,n1000)
etc.
You may not have to make several queries at all depending of the (characters?) limitations you face.
There are a lot of optimiziation tips, but for your specific case, here are 2:
Try to do everything in one go, #Jodrell suggested very good ideas for that.
Retrieve the smallest possible data from the db, select only the fields you need.

Using Contains() in a Where LINQ query

I'm using this piece of code to get a desired list of rows from a table:
_userObjectSet = EntityFrameWorkContext.CreateObjectSet<User>();
List<int> selectedUserIDs = Method(); //Returns a specific set of int user IDs...
var results = _userObjectSet.Where(c => selectedUserIDs.Contains(c.ID)).ToList();
This does work as 'results' will only contain records whose ID field matches an element in the selectedUserIDs list.
The problem is that, if I look at Windows Task Manager, LINQ seems to load ALL of the table's row THEN filter them out. There is a huge number of rows in this table, and pretty soon the process weights over 1GB, which I don't really like.
I can also tell that it's doing this because of the time it takes to complete.
Is there any way to tell LINQ to generate a query that would look like:
SELECT * FROM Users WHERE ID IN (34,55,66,77, etc.)
which would only return the exact rows I'm looking for and use less memory ?
Thanks!
Try join.. I think u can find a difference...
List<int> selectedUserIDs = Method(); //Returns a specific set of int user IDs...
var results = (from u in _userObjectSet
join id in selectedUserIDs on u.Id equals id
select u);
You're going to need something like LinqKit for this.Specifically, have a look at the PredicateBuilder that comes with the kit, as I think you need that to solve your problem.

LINQ to SQL, condition on foreign entities

In SQL, it'd be done as such:
SELECT * FROM Student
WHERE SchoolId IN
(SELECT id FROM School WHERE Name LIKE '%elementary%')
How do I implement this with LINQ? I've tried the following:
var list = context.Students.Where(x => context.Schools.Where(r => r.Name.Contains("elementary").Select(r => r.Id).Contains(x.SchoolId))
but it's not giving me what I want, unfortunately...
I know it's possible to retrieve all the Ids from the School table first, but I think it'd take a heavy toll on the performance. Preferably I'd like LINQ to SQL to handle everything; I can't do this using vanilla SQL because I need stuff to be dynamic and currently LINQ is the best solution for me.
The code above is all for illustration purposes; what I'm doing is a tad different (but more or less the same). I really do need some help on this; if you need any more information just feel free to ask.
EDIT: My bad, I missed out a field. It works, but the results didn't show up because I was missing that field... So sorry...
Try this:
var result = from st in context.Student
from sc in context.Schools
where sc.Name.Contains("elementary") && sc.SchoolId == st.SchoolId
select st;
I am a bit hazy on the syntax, pardon me. But this should point you to the right direction.
Something like this should work. The first use of Contains is on a string object to see if the string contains the substring "elementary". The second use of Contains is on a list and checks to see if the first result list contains SchoolId.
var sublist = from s in context.Schools
where s.Name.Contains("elementary")
select id;
var list = from s in context.Students
where sublist.Contains(s.SchoolId)
select s;

Categories