0

I have two lists.

  1. List of new categories that will be inserted into the database.
  2. List of categories that already exist in the database.
    public class Category{ 
    public string Name;
    }

    list<Category> dbCategories = new List(new Category{Name="John"}, new Category{Name = "Daniel"}, new Category{Name = "Matthew"});  

list<Category> newCategories = new List(new Category{Name="John"}, new Category{Name="Rock"}, new Category{"Daniel"});

I want to prevent duplicates in the database based on Name

I fetch the categories list from the database. and now want to check if the list of new categories to be inserted have a matching name in the database categories.

  • If the new categories have a name match in the database category list, I want to remove the category from the new Categories List that are to be inserted.
  • I want to retrieve an Item matching Name, first search must be made on 1st List, If no match is found ,then 2nd List should be searched.

How do I achieve this?

sham
  • 691
  • 8
  • 28
  • Possible duplicate of [LINQ's Distinct() on a particular property](http://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property) – Mohammad May 11 '17 at 08:10
  • if `Name` is private, how do you intend to access it? Can you change it? – Mong Zhu May 11 '17 at 08:14
  • This question I posted a long time ago, may be of some use to you. It's not in c#, but my ideas and routines are thoroughly discussed. http://stackoverflow.com/questions/14628834/compare-listview-items-in-two-adjacent-listviews-and-do-stuff-with-identical-it – Louis van Tonder May 11 '17 at 08:21

2 Answers2

2

You could use a combination of Where() and Any(), for example:

var newEntries = newCategories.Where(n => !dbCategories.Any(d => d.Name == n.Name));

Otherwise, you could look into using Except() using the IEqualityComparer overload to check equality based on Name.

Oliver
  • 8,794
  • 2
  • 40
  • 60
0

The easiest way would be to use a simple reversed for-loop and remove every item which is contained in the categories list. Here is a small programm to illustrate this:

void Main()
{
    List<string> categories = new List<string>() { "cat1", "cat2", "cat3" };
    List<string> tobeinserted = new List<string>() {"cat14", "cat2", "cat34"};

    for (int i = tobeinserted.Count-1; i >= 0 ; i--)
    {
        if (categories.Contains(tobeinserted[i]))
        {
            tobeinserted.RemoveAt(i);
        }
    }       
    Console.WriteLine(string.Join(Environment.NewLine, tobeinserted));      
}

output is:

cat14
cat34

To adjust it to your code the loop could look like this:

List<string> dbCategories_Names = dbCategories.Select(x => x.Name).ToList();

for (int i = newCategories.Count-1; i >= 0 ; i--)
{
    if (dbCategories_Names.Contains(newCategories[i].Name))
    {
        newCategories.RemoveAt(i);
    }
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76