Tanwer
Tanwer

Reputation: 1583

Distinct on multiple fields

I Have a List of some Properties as Model

public class AnswerList {
    public int ID { get; set; }
    public int? Schedule_ID { get; set; }
    public int? SubItemID { get; set; }
    public string SubItemName { get; set; }
    public string ItemName { get; set; }
    public string Answer { get; set; }
    public string Remarks { get; set; }
    public string Remarks_Flag { get; set; }
    public string Lattitude { get; set; }
    public string Longitude { get; set; }
    public DateTime? Load_Date { get; set; }
}

I was getting list of Distinct Sub Items from this List

List<string> sub_item_list = AnswerList.Select(x => x.SubItemName).Distinct().ToList();

Now I want data in different format as per below class

public class SubItemList {
    public string ItemName { get; set; }
    public string SubItemName { get; set; }
}

My requirement is to get distinct sub item with their respective Item Names , Sub Item should be distinct but Item Name can be repeated as one Item can contain multiple Subitem

Distinct Does not work on multiple values so I tried

List<SubItemList> SI_List = 
                 AnswerList.GroupBy(d => d.SubItemID)
                           .Select(x => 
                               new SubItemList 
                         { 
                          ItemName = x.Select(a => a.ItemName).First(), 
                          SubItemName = x.Select(a => a.SubItemName).First() 
                         }).Distinct().ToList();

This way I am getting what I want but I don't think its a preferable approach , Linq expression inside another Linq expression

How can I get it with a simple Linq expression ?

I am using ASP.Net Core 2.0

Upvotes: 2

Views: 5918

Answers (2)

ocrenaka
ocrenaka

Reputation: 192

Try with

GroupBy(
        p => new {p.ItemName, p.SubItemName}
       ).Select(g => new { g.Key.ItemName, g.Key.SubItemName });

Upvotes: 1

Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

If the expectation is what you have asked in the question, then following shall be the query:

AnswerList.GroupBy(d => new { d.SubItemID, d.ItemName, d.SubItemName})
                         .Select(x => new SubItemList{
                                     ItemName = x.Key.ItemName, 
                                     SubItemName =x.Key.SubItemName
                            }
                  ).Distinct();

How it works

  1. GroupBy unique combination of SubItemID, ItemName, SubItemName, which will form the grouping key
  2. Now only Pick the ItemName, SubItemName to create SubItemList and call Distinct to remove duplicates even across SubItemID

For Distinct to work correctly for the class SubItemList either implement IEquatable<SubItemList> or supply the IEqualityComparer<SubItemList> to the Distinct

Upvotes: 2

Related Questions