Hi i have a linq query below
var Free = (from row in
dt.AsEnumerable()
where row.Field("AppointmentType")
== "FreeTime"
select new{ row.Field("BookedDate")
row.Field("TravelTime")}).Min()
what i want to do is have a minimum on the travelTime field and im not sure on how to do it i have looked on google and also on the msdn site but i cant seem to make head or tail of it
does anyone have any ideas??
Many thanks
You could use an overload for Enumerable.Min():
var Free = (
from row in dt.AsEnumerable()
where row.Field("AppointmentType") == "FreeTime"
select new {
BookedDate = row.Field("BookedDate"),
TravelTime = row.Field("TravelTime")
}
).Min(x => x.TravelTime);
Actually, there is no need to look at the BookedDate and you should instead use
var Free = (
from row in dt.AsEnumerable()
where row.Field("AppointmentType") == "FreeTime"
select row.Field("TravelTime")
).Min();
I kept your original code with a few modifications to demonstrate the syntax for creating anonymous types.
Related
I'm trying to learn LINQ. I have
var mydata = from k in db.emp_mains select k.empname.Equals("me");
But after this statement i the auto complete wont complete the table fields name
foreach(var x in mydata)
{
---> Autocomplete not working Console.WriteLine(x.empname);
}
Why is this happening? Kindly advice.
Your condition need to go into where clause
var mydata = (from k in db.emp_mains
where k.empname.Equals("me")
select k
).ToList();
What you want is to filter with the where statement:
var myData = from k in db.emp_mains
where k.empname == "me"
select name
I much prefer the linq syntax like this for simple statements however:
var myDate = dc.emp_mains.where(w => w.empname == "me").Select(s => s.name).ToList();
Either way, you should get a list on names.
I'm working in asp.net web forms 4.5 version.
I have trouble with linq.
I want to bring a table data.. (I don't want to join it.. as I would want it to be deleted and edited by the autodelete and autoedit button of gridview)
But I'm lost with linq.
I would like to do something like this..
public Iqueryable detailGrid_getData(){
string fromDStr = fromTBox.Text;
DateTime fromD = Convert.ToDateTime(fromDStr);
string toDStr = toTBox.Text;
DateTime toD = Convert.ToDateTime(toDStr);
var items = from s in db.salesOrderDetail_T where
db.salesOrder_T
.Select(so => so.poDate <= toD && so.poDate >=fromD)
.Contatins(s.soIdx) && s.stat == stat;
return items;
}
at which I got the idea from here : LINQ, select ID from Table where it does not match ID in another table
but for some reason, it doesn't work.
Will someone tell me why this is not working??
edit : It says a query body must end with a select clause or a group clause
The error message is quite clear here. Your query (items) does not end in a select clause, I think this is what you want:
var items = from s in db.salesOrderDetail_T where
db.salesOrder_T.Where(so => so.poDate <= toD && so.poDate >=fromD).Select(p=>p.Id).Contains(s.soIdx)
&& s.stat == stat
select s;
I would like to answer this because I figured it out totally different way.
Turns out that in LINQ, I can get around things in a lot of way.
This is the way I got through this..
Still not that expert in LINQ, but getting it.
var items = from so in db.salesOrderDetail_T
where so.poDate <= toD && so.poDate >= fromD
select so.idx;
soIdxList = items.toList();
items = items.Where(it => soIdxList.Contains((int) it.soIdx)
and then, use it.
Again, I'm not sure this is a good way to do things,
but it's easy and works.
I am trying to mimic below statement in Linq to SQL.
WHERE (rtrim(posid) like '%101' or rtrim(posid) like '%532')
I statement basically determine if posid ends with 101 or 532. In the above example I am only making 2 comparisons but their could be 1 to N comparisons all joined with OR. I store the comparison values (101,532,...) in a generic list that I send to my Linq to SQL method.
I have tried to mimic above SQL using a where clause unsuccessfully (example below):
var PosNum = new List<string>();
PosNum.Add("101");
PosNum.Add("532");
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => PosNum.Contains(p.posid.Trim()));
The issue with the above where clause is that it tries to do an exact match rather I want an ends with comparison.
How would I mimic the SQL statement in Linq to SQL.
Thank You in advance for any help / advice you can provide.
I would use String.EndsWith();
This will check the end of the string rather than entire contents of it.
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => p.posid.EndsWith("102") || p.posid.EndsWith("532"));
In EF 4 you can use the StartsWith / EndsWith methods by now. Might also work in LINQ to SQL.
UPDATE
Just realized that you are trying todo this against multiple values (PosNum), I don't think that this is directly supported currently. You can however concatenate multiple Where()clauses to get the result.
UPDATE 2
As AdamKing pointed out concatenating the where clauses was filtering against all PosNum values, here is the corrected version:
var baseQuery = (from a in context.tbl_sspos select a);
IEnumerable<YourType> q = null;
foreach(var pos in PosNum)
{
if(q == null)
q = baseQuery.Where(a => a.posid.EndsWith(pos));
else
q = q.Union(baseQuery.Where(a => a.posid.EndsWith(pos)));
}
This is not as pretty anymore, but works nonetheless.
What I'm trying to do is narrow the results of a query that I will use to databind later on. I want to get all of the ProgramIds that are used in my gridview, and remove them from the datasource of my dropdownlist (ie, so that a user cannot choose to create and insert an object into the gridview of the same ProgramId as one that already exists)
Here's some code:
var query = from goals in DataContext.Goals
select goals;
var query2 = (from goals in query.AsEnumerable()
select goals.ProgramId).ToList(); //List<long?>
var query3 = (from progs in DataContext.Programs
select progs.ProgramId).ToList(); //List<long>
var cgps = query3.Except(query2);
And I'm getting these errors on var cgps = query3.Except(query2); :
Error 29 'System.Collections.Generic.List' does not contain a definition for 'Except' and the best extension method overload 'System.Linq.ParallelEnumerable.Except(System.Linq.ParallelQuery, System.Collections.Generic.IEnumerable)' has some invalid arguments C:...\Shmeh\Shmeh\Shmeh\this.aspx.cs 24 226 Project
Error 30 Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.ParallelQuery' C:...\Shmeh\Shmeh\Shmeh\this.aspx.cs 24 226 Project
If you have any idea how to validly do what I'm trying to do, any help would be greatly appreciated! Thanks!
Except requires that the sequences are both of the same type. Try casting the long list to long?:
var query3 = (from progs in DataContext.Programs
select (long?)progs.ProgramId).ToList(); //List<long?>
You're getting this error because long? is not the same type as long. Except requires both enumerable objects to be of the same type.
What you could do is remove the null values from query2 and convert ProgramId to long
var query2 = (from goals in query.AsEnumerable()
where goals.ProgramId.HasValue
select goals.ProgramId.Value).ToList()
try
var cgps = query3.Cast<long?>().Except(query2);
var cgps = DataContext.Programs.Select(p => p.ProgramId)
.Except(DataContext.Goals.Where(g => g.ProgramId.HasValue).Select(g => g.ProgramId.Value));
I don't know if this will work for you.
var query2 = (from goals in query.AsEnumerable()
select goals.ProgramId).ToList() as List<long?>;
var query3 = (from progs in DataContext.Programs
select (long?)progs.ProgramId).ToList() as List<long?>;
I don't know why he/she deleted their answer, but I'm using this:
dropdownlist.DataSource = (
from progs in DataContext.Programs
where !(from goals in query.AsEnumerable()
select goals.ProgramId)
.Contains(progs.ProgramId)
select progs.Name).ToList();
dropdownlist.DataBind();
Because it doesn't require me to use multiple query variables, although the answer I accepted worked as well with what I had.
How would I do a linq query like this
For example I want to count up all the numbers in a column and for it to return the result of them being added up
Thanks
var count = mytable.Sum(t => t.myCol);
I find the LINQ to SQL samples site on MSDN to be an excellent reference for basic questions like this.
The Simple Sum example there is probably what you want:
// This sample uses Sum to find the total freight over all Orders.
void LinqToSqlCount03()
{
var q = (from o In db.Orders
select o.Freight).Sum()
}
Try the following:
numbers.Sum(n => n.Value);
Here we go:
DbContextName = dbTableName.Count(x=>x.columnName);