0

I've got a problem and need some help. I've got a list of objects which have many properties, but only two are important "From" and "To".

objectData { "From" : "ContactDTO", "To" : ["ContactDTO"], ...//other fields }

contactDto { "email" : "string", ... other fields }

and I need to return new list with unique entries "From", array of contacts "To" without duplicates.

Test Data:

{ 
   "From": { "email" : "[email protected]"}, 
   "To": "[{ "email" : "[email protected]"}, { "email" : "[email protected]"}]"
},
{ 
   "From": { "email" : "[email protected]"}, 
   "To": "[{ "email" : "[email protected]"}, { "email" : "[email protected]"}]"
},
{ 
   "From": { "email" : "[email protected]"}, 
   "To": "[{ "email" : "[email protected]"}, { "email" : "[email protected]"}]"
},

Should Return:

[
"From": { "email" : "[email protected]"}, 
   "To": "[{ "email" : "[email protected]"}, { "email" : "[email protected]"}, { "email" : "[email protected]"}]"
{ 
   "From": { "email" : "[email protected]"}, 
   "To": "[{ "email" : "[email protected]"}, { "email" : "[email protected]"}]"
}
]

I know how to do it in a loop, but I would like to make it more readable and clean with using linq.

I've tried:

var newData = data.Where(x => IsReview(x))
                .Select(x => 
                new { 
                    From = x.From.EmailAddress, 
                    List = x.To.Select(z => z.EmailAddress).ToList() 
                }).GroupBy(y => y.From);
2
  • What issue you faced in your attempt? Do you want unique email addresses in List? Commented Jun 20, 2020 at 17:25
  • 1
    Well u r almost there, try adding select to groupby. Inside select apply selectmany to flatten the emails followed by distinct Commented Jun 20, 2020 at 17:34

1 Answer 1

2

You could Select new object after GroupBy and use SelectMany to flatten emails in one list, like the following code:

var newData = data.Where(x => IsReview(x))
    .Select(x => new 
    { 
        From = x.From.EmailAddress, 
        List = x.To.Select(z => z.EmailAddress).ToList() 
    }).GroupBy(y => y.From)
    .Select(x => new
    {
        From = x.Key,
        To = x.SelectMany(y => y.List).ToList()
    });

I hope you find this helpful.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your help, I've modified it a bit, but manage to get it working. I'm marking your answer as correct one, have a great day.
you're welcome, was glad to help, have a good day too.

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.