David
David

Reputation: 55

Distinct rows from db table with unique IDs but same names

I am creating a videorental system and I'm told that there are to be multiple entries of the same movie, as in a real videostore, but they should all have unique IDs. I'm using LINQ to fetch the data, and currently my view shows me the entire table, so the same movie name gets repeated alot. I tried using the .Distinct extension method, but since the IDs are not the same, they are all distinct. I need to ignore the ID portion of the object, but can't figure it out.

    public static List<Movie> GetAllMovies()
    {
        return Context.Movie.ToList();
    }
    public static List<Movie> GetAllMoviesDistinct()
    {
        return Context.Movie.Distinct().ToList();
    } 

These two methods do the exact same thing

Upvotes: 1

Views: 59

Answers (4)

Bondaryuk Vladimir
Bondaryuk Vladimir

Reputation: 519

var groupesList = Context.Movie.GroupBy(x => x.Name,
     (key, val) => new {Key = key, Value = val}).ToList();

then you can call Key(unuque) or Value by key for all inform for example all ID

Upvotes: 0

Andrei V
Andrei V

Reputation: 7508

You'd need something like this:

public static List<string> GetAllMovieTitlesDistinct()
{
     return Context.Movie.GroupBy(x => x.Title).Select(x => x.Key).ToList();
}

Since you have multiple entries for the same movie, it doesn't really make sense to return a random (or just the first) movie with a specific name. What I'd rather do, is get the unique movie titles, select one title and then list all the entries for that.

What the method above does is, it groups all the movies by their names and then just selects each unique movie title. Please note that it does not return a specific entry for each title, as that would be highly arbitrary and might lead to unwanted results.

Upvotes: 1

Marcin J
Marcin J

Reputation: 378

You can use GroupBy to get movies with for example unique name.

return Context.Movie.GroupBy(m => m.Name).Select(x => x.First()).ToList();

Upvotes: 1

stefankmitph
stefankmitph

Reputation: 3306

You can do this with MoreLINQ:

var result = Context.Movie
                    .DistinctBy(m => new {
                                            // take all properties except your ID
                                         })
                    .ToList();

Upvotes: 1

Related Questions