0

In C#, I have one foreach loop.

foreach (businfo ibusinfo in lclbbusinfo)
{
    ibusinfo.Updateperson();
}

lclbbusinfo -> contains the column member_id and other releavnt columns

updateperson() - > method which will update the member_id(primary key) information like name ,phone etc.

Most of the cases lclbusinfo will have different member_id's so it will update the member's information accordingly in for each loop.

In rare scenario sometimes the lclbbusinfo will have same member_id's. In that case, the first iteration will update the member table and then the next (or 3rd or 4th, etc.) will also try to update the same member info again in the same table.

So how do we avoid updating the same member id again and again?

I have tried using ibusinfo to check previous member_id only.

Domnic
  • 3,817
  • 9
  • 40
  • 60

3 Answers3

1

If you only want to update the first businfo object of those that have the same member_id, you may use something like this:

foreach (businfo ibusinfo in lclbbusinfo.GroupBy(x => x.member_id)
                                        .Select(g => g.First()).ToList())
{
    ibusinfo.Updateperson();
}

This will group the elements of lclbbusinfo that have the same member_id and only select the first one of them to be used by the foreach loop.

1

A GroupBy() over your collection is good enough. But if you are looking for multiple ways to implement duplicate check, you can separately maintain a HashSet<int> yourself while iterating over the collection.

HashSet<int> unique = new HashSet<int>();

foreach( var item in lclbbusinfo )
{
    if(unique.Add(item.member_id))
    {
        item.Updateperson();
    }
}

Updated example to take comment into account.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • [Adding](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.add?view=netframework-4.8) to the `Hashset` will return a boolean value, so instead of doing the contains why not check the value returned from the `Add(value)` and just update the person? – Diego Osornio Oct 23 '19 at 19:22
-1

Try this one. add namespace => using System.linq;

        List<member_id_dataType> member_idList = lclbbusinfo.Select(x => 
        x.member_id).Distinct().ToList();
        foreach (var ibusinfo in lclbbusinfo)
        {
            if (member_idList.Contains(ibusinfo.member_id))
            {
                ibusinfo.Updateperson();
                member_idList.Remove(ibusinfo.member_id);
            }
        }
  • `Distinct()` does not take a lambda expression as argument. Your answer is invalid, it won't even compile. Although, I wish it was an option. – Tanveer Badar Oct 24 '19 at 04:07