0

I have this method

Meeting is a class
Attendees is an ICollection in Meeting

Class

public partial class Meeting
    {

        public Meeting()
        {
            this.Attendees = new List<Attendees>();
        }

public virtual ICollection<Attendees> Attendees{ get; set; }
[...]

Method Controller

private void RemoveRowsDuplicated(Meeting model)
        {
            if (model.Attendees != null)
            {
                foreach (var item in model.Attendees.GroupBy(x => x.UserName).Select(y => y.Last()))
                {
                    context.Attendees.Remove(item);
                }
            }
        }

The objective is remove duplicate Attendees with the same username in the table.
But the current method it deletes all records and keeps the duplicate
Where am I going wrong?

1

3 Answers 3

3

Correct version of your method will look like this:

private static void RemoveRowsDuplicated(Meeting model)
        {
            if (model.Attendees != null)
            {
                var duplicates = new List<Attendees>();
                foreach (var item in model.Attendees.GroupBy(x => x.UserName).Where(x=>x.Count()>1))
                {
                    duplicates.AddRange(item.Skip(1));
                }
                duplicates.ForEach(x=>context.Attendees.Remove(x));
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

0

You can try writing raw SQL and invoking via EF and return Attendees objects in a list.

var query = "Select * from Attendees group by username";
var attendeesList = dbContext.Database.SqlQuery<Attendees>(query).ToList<Attendees>();

Comments

-1

As I can see you grouped elements by name and remove last item. So you remove unique elements. Like this

 private void RemoveRowsDuplicated(Meeting model)
        {
             if (model.Attendees != null)
             {
                var temporaryAtendees = new List<Attendees>();
                foreach(var item in model.Attendees)
                {
                    if (temporaryAtendees.Contains(item))
                    {
                        context.Attendees.Remove(item);
                    }
                    else
                    {
                        temporaryAtendees.Add(item);
                    }
                }
                }
            }

1 Comment

Yes I see now you have other question and my answer not about this

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.