I have a "Tickets" table with somewhat following structure (removed unnecessary columns)
int | string | int | ID | Window | Count | ------------------------ 0 | Internet | 10 | 1 | Phone | 20 | 2 | Fax | 15 | 3 | Fax | 10 | 4 | Internet | 5 | . | . | . | . | . | . |
And I have mapped this table to a class "Ticket". So I can get all records like this:
var tickets = from t in db.Tickets select t;
Now I need to get the list of unique window names in the table. For above table, list would look something like:
Is there anyway to create this list without fetching all records and iterating over them?
I am using SQL Server 2008 express edition.
EDIT: Thanks for the answers guys it solved the above problem. Just being greedy but is there any way to also get the total of count for each window. For example:
How about:
var tickets = db.Tickets.Select(t => t.Window).Distinct();
I prefer to only use query expressions when I'm doing more than one operation, but if you like them the equivalent is:
var tickets = (from t in db.Tickets
select t.Window).Distinct();
To get the counts, you need to group:
var tickets = from t in db.Tickets
group t by t.Window into grouped
select new { Window=grouped.Key,
Total=grouped.Sum(x => x.Count) };
foreach (var entry in tickets)
{
Console.WriteLine("{0}: {1}", entry.Window, entry.Total);
}
Note that this should all end up being performed at the database side - examine the SQL query to check this.
var query2 = from ticket in db.tickets
group window by ticket.Window into result
select new
{
Name = result.Window,
Sum = result.Sum(i => i.Count)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With