0

I have a list with elements where an element is a class of some string and datetime values. I have the situation that some elements in the list are the same, but I only want the unique entries. I have tried the following but to no results. And I have verified that there are double entries. These are some snipets:

  public class RunningProcess
{
    public string PSComputerName { get; set; }
    public string ProcessName { get; set; }
    public string ProcessID { get; set; }
    public string CommandLine { get; set; }
    public Nullable<System.DateTime> CreationDate { get; set; }
    public string Username { get; set; }
    public string RemoteIP { get; set; }
}

now:

  l_runningprocesses = l_runningprocesses.Distinct().ToList();

or

  var unique_items = new HashSet<RunningProcess>(l_runningprocesses);

or

  List<RunningProcess> uniques = new List<RunningProcess>();
  foreach (RunningProcess item in l_runningprocesses)
  {
      if (!uniques.Contains(item)) uniques.Add(item);
  }

All the same. I keep the doubles. Any ideas anyone??

Regards,

Ronald

Ronald
  • 1,083
  • 3
  • 13
  • 20
  • 5
    You have not defined Equals and GetHashCode for your class, thus entries are compared by references - if references are different, then entries considered different (even if all field values are equal) – Sergey Berezovskiy Jan 02 '14 at 14:56
  • 5
    You need to be more specific on what you consider distinct, in this case `ProcessID` will always be different, so the distinct list should be the same as the non-distinct list. – asawyer Jan 02 '14 at 14:56
  • l_runningprocesses ? what is its type , – Binson Eldhose Jan 02 '14 at 15:01

2 Answers2

1

Distinct is comparing on object references , not the content of your object. You have to write an EqualityComparer and then use the overload of distinct.

An easy alternative is:

l_runningprocesses=l_runningprocesses
  .GroupBy(item=>item.ProcessID)
  .Select(group=>group.First())
  .ToList();
MichaelD
  • 8,377
  • 10
  • 42
  • 47
1
l_runningprocesses = l_runningprocesses.Distinct().ToList();

will not give you distinct objects. .Distinct() will work for list of int, double or in places like Linq to SQL, EntityFramework.

One way of doing it is to write your own IEqualityComparer

public class RunningProcessComparer : IEqualityComparer<RunningProcess>
{
    public bool Equals(RunningProcess x, RunningProcess y)
    {
        return x.ProcessID == y.ProcessID;
    }

    public int GetHashCode(RunningProcess obj)
    {
        return obj.ProcessID.GetHashCode();
    }
}

then use it as

l_runningprocesses = l_runningprocesses.Distinct(new RunningProcessComparer());
Amila
  • 3,711
  • 3
  • 26
  • 42