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.

1

3 Answers 3

2

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

list.Select(x => new {x.Name, x.Description}).Distinct();
Sign up to request clarification or add additional context in comments.

1 Comment

However we don't know if the OP wants also the other informations present in its items.
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

4 Comments

Why copy/pasting from another answer? Just close as duplicate or post a comment.
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.
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. .
I think you are missing the point :-) Please read the answer and my previous comments fully.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.