1

Consider objModels is object of ChildModel class

public class ChildModel
{
public string Title { get; set; }
public long Id { get; set; }
}

It has some data like: title,id: a,1 b,1 a,1

Two of these data are same, and after distinct it could be like: a,1 b,1

Question is how could I distinct it on c#

List<ChildModel> obj= objModels.ToList();

Also these aren't help

objModels.Distinct();
obj.Distinct();
asa
  • 83
  • 1
  • 7

4 Answers4

1

You could use a library named MoreLINQ

This is the query you could use with MoreLINQ to find elements that are distinct by multiple properties:

var query = objModels.DistinctBy(p => new { p.Id, p.Title});
sachin
  • 2,341
  • 12
  • 24
0

you can use .GroupBy:

var result= obj
  .GroupBy(p => p.Title)
  .Select(g => g.First()) // choose which one
  .ToList();

edit: if you want to GroupBy more than one Property you can just change p.Title to new {p.Title, p.Id} like so

var result= obj
  .GroupBy(p => new {p.Title, p.Id})
  .Select(g => g.First()) // choose which one
  .ToList();
WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32
0

try this:

var answer= obj.DistinctBy(p => new { p.Id , p.Title });

and check this link for other way

Shahrooz Ansari
  • 2,637
  • 1
  • 13
  • 21
0

I would do the following:

            namespace ConsoleApplication7
            {
                class Program
                {
                    static void Main()
                    {
                        List<ChildModel> list = new List<ChildModel>();
                        list.Add(new ChildModel { Title = "a", Id = 1 });
                        list.Add(new ChildModel { Title = "b", Id = 1 });
                        list.Add(new ChildModel { Title = "a", Id = 1 });

                        var x = list.Distinct(new ChildModelComparer()).ToList();

                        var y = x; //This has only got two child items.

                    }
                }
                class ChildModelComparer : IEqualityComparer<ChildModel>
                {
                    public bool Equals(ChildModel x, ChildModel y)
                    {
                        return x.Id.Equals(y.Id) && x.Title.Equals(y.Title);
                    }

                    public int GetHashCode(ChildModel obj)
                    {
                        if (string.IsNullOrEmpty(obj.Title) && obj.Id == 0)
                        {
                            return 0;
                        }
                        return $"{obj.Id}{obj.Title}".GetHashCode();
                    }
                }
                public class ChildModel
                {
                    public string Title { get; set; }
                    public long Id { get; set; }
                }
            }
Mobaruk H
  • 54
  • 1
  • 7