2

I currently have a list containing items which have fields: "name, description, source, title, ...". I want to dump a list from this, but solely unique based on two keys, the name and description. Basically, I don't want items from the list with the same name and the same description, but if they have different names and the same description, then it's fine.

I looked up that using

 list.select(x => x.Name).Distinct() 

would give me a list with distinct name, but stacking them would violate having one of the unique keys different, and one the same.

I also took a look into hash sets, but I'm completely confused on how that works.

If anyone could help, it would be greatly appreciated.

3 Answers3

2

If you're just looking for all distinct name/description combinations:

list.Select(x => new {x.Name, x.Description}).Distinct();
Kyle W
  • 3,702
  • 20
  • 32
  • However we don't know if the OP wants also the other informations present in its items. – Steve Jan 15 '16 at 08:26
0

You can either use the following example taken from HERE:

IEnumerable<Person> filteredList = originalList
  .GroupBy(person => person.Name)
  .Select(group => group.First());

Or use DistinctBy from MoreLINQ NuGet available HERE

Community
  • 1
  • 1
  • Why copy/pasting from another answer? Just close as duplicate or post a comment. – Steve Jan 14 '16 at 22:02
  • 1
    This answer is adapted to the OPs question, the link to the other answer is clearly included here also an alternative solution is provided so I do not believe posting a comment would be appropriate. –  Jan 14 '16 at 22:30
  • Sorry but I stand on my opinion. If you think that the link solves the problem with all the answers present there then it is a duplicate. If you think not, then a comment is enough. Just changing a variable name doesn't make this a substantial different answer. . – Steve Jan 14 '16 at 22:37
  • 1
    I think you are missing the point :-) Please read the answer and my previous comments fully. –  Jan 14 '16 at 22:38
0
var uniqueData = list.Select(x => new
            {
                UniqueKey = x.Name + " " + x.Description,
                Data = x,
            }).GroupBy(x => x.UniqueKey)
                .Select(g => g.First().Data)
                .ToList();

You should probably use some unique/special character/string instead of " " to make sure UniqueKey is really unique.

serhiyb
  • 4,753
  • 2
  • 15
  • 24