1

How can I get unique records from database by linq?

For example: I have something like that

07.12.2016
07.12.2016
08.12.2016
08.12.2016
10.12.2016

I would like to have something like that

07.12.2016
08.12.2016
10.12.2016

My query:

var query2 = (from availableDate in bazaDC.seanses
                        where availableDate.id_filmu == id
                        orderby availableDate.data ascending
                        select availableDate.data).Distinct();
availableDate.DataSource = query2;
availableDate.DataBind();

And html:

<asp:Repeater ID="dostepneDaty" runat="server">
    <ItemTemplate>
        <a href="repertuar_szczegoly.aspx?id=<%# Eval("id_filmu") %>&&data=<%# Eval("data","{0:dd.MM.yyyy}") %>"><%# Eval("data","{0:dd.MM.yyyy}") %></a><br />
    </ItemTemplate>
</asp:Repeater>

Distinct() doesnt work.

And Im going to include table definition:

CREATE TABLE [dbo].[seanse] (
    [id_seansu] INT      IDENTITY (1, 1) NOT NULL,
    [godzina]   TIME (7) NOT NULL,
    [data]      DATE     NOT NULL,
    [id_filmu]  INT      NOT NULL,
    PRIMARY KEY CLUSTERED ([id_seansu] ASC),
    CONSTRAINT [FK_seanse_ToTable] FOREIGN KEY ([id_filmu]) REFERENCES [dbo].[filmy] ([id_filmu])
);

Any ideas?

Daniel
  • 9,491
  • 12
  • 50
  • 66
  • 2
    Is `GroupBy()` appropriate? [MSDN](https://msdn.microsoft.com/en-us/library/system.linq.enumerable.groupby(v=vs.110).aspx), [SO](http://stackoverflow.com/questions/7325278/group-by-in-linq) – vbnet3d Dec 23 '16 at 17:06
  • 2
    Easiest way would be using GroupBy – Christian Klemm Dec 23 '16 at 17:07

3 Answers3

4

From what I know your select distinct should work, but you can always do the same thing by grouping and selecting the first element.

Examples Below:

Select Distinct:

 var query2 = bazaDC.seanses
             .Where(availableDate => availableDate.id_filmu == id)
             .Select(x => x.data)
             .Distinct()

Group By:

 var query2 = bazaDC.seanses
             .Where(availableDate => availableDate.id_filmu == id)
             .GroupBy(x => x.data )
             .Select(g => g.First())
2

Try this piece of code

 var query2 = (from availableDate in bazaDC.seanses
                     where availableDate.id_filmu == id
                     group availableDate by new { availableDate.id_filmu, availableDate.data } into g
                     orderby availableDate.data ascending
                     select new { g.Key.id_filmu, g.Key.data});   

You're adding the group by clause so it will retrieve unique values

1

I created a dotnetfiddle example showing it working as expected. Below is the LINQ statement used in that example.

IEnumerable<DateTime> dataSource = (from availableDate in seanses
    where availableDate.id_filmu == 1
    orderby availableDate.data
    select availableDate.data).Distinct();
Andy
  • 648
  • 8
  • 21