-2

I have the OccupancyResultList list

 List<Occupancy> occupancyResultList = new List<Occupancy>();

of Occupancy

public partial class Occupancy
{
    public Nullable<System.DateTime> on_date { get; set; }
    public string type_code { get; set; }
    public Nullable<int> available { get; set; }
    public Nullable<decimal> rate { get; set; }
    public string rate_code { get; set; }
    public string publish_flag { get; set; }
}

I want to create another list that has the distinct values of on_date,type_code,available

Distinct() produces a distincted result of all columns which returns repeatitions.

Can you give me a hand plz?

Thanx in advance!

PanosPlat
  • 940
  • 1
  • 11
  • 29
  • see https://social.msdn.microsoft.com/Forums/en-US/ed38539f-fde4-4a2a-8e80-d058c32b332b/linq-select-distinct-c – Amit Kumar Ghosh Jul 09 '15 at 07:07
  • If there are multiple Occupancy objects that have the same values for `on_date`, `type_code`, and `available`, which one do you want to show up in the results? – Jerry Federspiel Jul 09 '15 at 07:08
  • 1
    see http://stackoverflow.com/questions/489258/linq-distinct-on-a-particular-property?rq=1 – Liem Do Jul 09 '15 at 07:19

1 Answers1

1

You can either use GroupBy with an anonymous type as a key:

occupancyResultList = occupancyResultList
        .GroupBy(x => new { x.on_date, x.type_code, x.available })
        .Select(g => g.First())
        .ToList();

Or DistinctBy method:

occupancyResultList = occupancyResultList
        .DistinctBy(x => new { x.on_date, x.type_code, x.available })
        .ToList();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • I get the following error in your second hint: System.Collections.Generic.List' does not contain a definition for 'DistinctBy' and no extension method 'DistinctBy' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?) – PanosPlat Jul 09 '15 at 07:12
  • 1
    you need to download MoreLINQ and add a reference – Selman Genç Jul 09 '15 at 07:13
  • Selmann22 will this be OK as well? var newList = occupancyResultList.Select(s => new { on_date = s.on_date, type_code = s.type_code, available = s.available }).Distinct(); – PanosPlat Jul 09 '15 at 07:20
  • 1
    that won't give you a list of occupancies but a list of anonymous type with just three properties. – Selman Genç Jul 09 '15 at 07:22