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);
Related
My sample data coloumn, which come from an CSV file is
|----Category------------|
SHOES
SHOES~SHOCKS
SHOES~SHOCKS~ULTRA SOCKS
I would love to split the specific column and get the distinct values in a list like
SHOES
SHOCKS
ULTRA SOCKS
I tried the following, but it does not work as expected.
var test = from c in products select c.Category.Split('~').Distinct().ToList();
It actually returns the following.
Any thoughts please? Thank you.
I would use SelectMany to "flatten" the list before removing duplicates:
products.SelectMany(c => c.Category.Split('~'))
.Distinct()
You can use SelectMany to flatten the collection:
products.SelectMany(p => p.Category.Split('~')).Distinct().ToList();
You were close, you just needed to flatten out your collection to pull the individual items of each grouping via a SelectMany() call :
// The SelectMany will map the results of each of your Split() calls
// into a single collection (instead of multiple)
var test = products.SelectMany(p => p.Category.Split('~'))
.Distinct()
.ToList();
You can see a complete working example demonstrated here and seen below :
// Example input
var input = new string[] { "SHOES","SHOES~SHOCKS","SHOES~SHOCKS~ULTRA SOCKS" };
// Get your results (yields ["SHOES","SHOCKS","ULTRA SOCKS"])
var output = input.SelectMany(p => p.Split('~'))
.Distinct()
.ToList();
Merge this list of list of strings into a single list by using SelectMany() and Just add another Distinct to your List..
var test = from c in products select c.Category.Split('~').Distinct().ToList().SelectMany(x => x).Distinct().ToList();
Here's how you'd do it in query syntax.
var test = (from p in products
from item in p.Category.Split('~')
select item).Distinct().ToList();
I'm wanting to only display a list of CourseNo with no duplicates using LINQ, but I can't quite figure the syntax out.
this.Distinct_CourseNo = (from c in Roster_Sections
select c).Distinct(CourseNo).ToList;
The SQL equivalent would be something along the lines of:
SELECT DISTINCT CourseNo
FROM Roster_Sections
All the provided answers are applicable only if you have moreLINQ. However, you can try this instead:
this.Distinct_CourseNo = (from c in Roster_Sections
group c by c.CourseNo into g
select g.First()).ToList();
using select c will include all columns in the Roster_Sections, thus Distinct() will not work if atleast one row in a column is different from the other row.
this.Distinct_CourseNo = (from c in Roster_Sections
select c.CourseNo).Distinct().ToList();
or
this.Distinct_CourseNo = Roster_Sections.Distinct(c => c.CourseNo).ToList();
You’d pass Distinct a lambda describing what defines distinctness:
this.Distinct_CourseNo = Roster_Sections.Distinct(x => x.CourseNo).ToList();
If you mean to get a list of unique course numbers as opposed to a list of unique courses based off course number, 今 草 顿 웃’s answer is the way to go.
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.
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.