List unique rows in a database table using Linq?

I have a "Tickets" table with the following structure (unnecessary columns removed)

int | string | int |
ID | Window | Count |
------------------------
0 | Internet | 10 |
1 | Phone | 20 |
2 | Fax | 15 |
3 | Fax | 10 |
4 | Internet | 5 |
. | . | . |
. | . | . |

And I matched this table with the "Ticket" class. Therefore, I can get all the entries:

var tickets = from t in db.Tickets
              select t;

Now I need to get a list of unique window names in the table. For the table above, the list will look something like this:

  • the Internet
  • Telephone
  • fax machine

Do I need to create this list at all without selecting all the entries and repeating them?

I am using SQL Server 2008 Express.

EDIT: , . , . :

  • = 15
  • = 25
  • = 20
+3
5

:

var tickets = db.Tickets.Select(t => t.Window).Distinct();

, , , :

var tickets = (from t in db.Tickets
               select t.Window).Distinct(); 

, :

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);
}

, - SQL-, .

+10
 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)
 };  
+3

11 . Distinct() Linq. .

var tickets = (from t in db.Tickets
               select t).Distinct();

[EDIT]

, . .

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 5 };

        var numberGroups =
            from n in numbers
            group n by 5 into g
            select g;

        g.Count(); // occurences
+1

.

var windows = db.Tickets.Select(ticket => ticket.Window).Distinct();
+1
source

You can use the .Distinct () operator - it will do a SELECT DISTINCT in the database, providing exactly what you ask.

0
source

Source: https://habr.com/ru/post/1708726/


All Articles