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?

tereško
  • 58,060
  • 25
  • 98
  • 150
O Aprendiz
  • 55
  • 3
  • 13
  • I believe, it was already answered here: http://stackoverflow.com/questions/1606679/remove-duplicates-in-the-list-using-linq – drcolombo Jan 14 '16 at 15:50

3 Answers3

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));
            }
        }
Mitklantekutli
  • 410
  • 1
  • 3
  • 16
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>();
jamdownian
  • 410
  • 3
  • 11
-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);
                    }
                }
                }
            }
AntonE
  • 632
  • 5
  • 13