GThree
GThree

Reputation: 3530

How to select unique list out of collection of lists?

I have a collection of IList where I can see duplicate set of List in it. How can I just select a unique list?

IList parameters,

IList<OrderItemModifier> Modifiers; 

public class OrderItemModifier
{
    public int Id { get; set; }
    public int MenuAnswerId { get; set; }
    public int DatabaseId { get; set; }
    public int Plu { get; set; }
    public decimal Price { get; set; }
    public string SpecialInstructions { get; set; }
    public string ModifierDescription { get; set; }
    public int Quantity { get; set; }
}

Now there is a scenario where Modifiers has two entries (as shown below) where both of them are same and I want to select unique out of it.

Example, Modifiers has two entries where [0] & [1] are exact same and I just want to pick unique one (here [0]).

[0] {OrderItemModifier} - Same values
[1] {OrderItemModifier} - Same values

I've tried following but it didn't work.

1.  
var uniqueModifiersList = newItem.Modifiers.Distinct().ToList();

2. 
HashSet<OrderItemModifier> uniqueModifiersList = new HashSet<OrderItemModifier>();
foreach (OrderItemModifier item in newItem.Modifiers)
{
    uniqueModifiersList.Add(item);
}

3.
HashSet<OrderItemModifier> uniqueModifiersList = new HashSet<OrderItemModifier>(newItem.Modifiers);

Any ideas?

Upvotes: 2

Views: 79

Answers (2)

deramko
deramko

Reputation: 2835

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class OrderItemModifier
{
    public int Id { get; set; }

    public override bool Equals(object obj)
    {
        var typedObj = obj as OrderItemModifier;
        return typedObj != null && typedObj.Id = this.Id;
    }

    public override int GetHashCode()
    {
        return this.Id;
    }
}

Now you can use Distinct:

List uniqueIDs = myList.Distinct().ToList();

Upvotes: 0

g williams
g williams

Reputation: 184

var filteredList = Modifiers
  .GroupBy(modifier => modifier.Id)
  .Select(chunk => chunk.First());

Upvotes: 4

Related Questions