-1

I use this piece of code to compare my two lists :

private void CompareLists(List<string> list1, List<string> list2)
{
    List<string> commonList = list2.Where(g => list1.Any(x => g.Contains(x))).ToList();
}  

list2 contains 15000+ items that are path to files located in my network that look like \\myserver\direcory\subdir\myfile.pdf

list1 contains items I get from an Excel sheet, for my test there are 29 items including 3 duplicates, they contain the 'myFile' part if what's in list2.

After my CompareLists function, commonList contains only 26 items, the 3 missing being the duplicates.
How can I modify my LINQ query to have those duplicates in commonList ?

EDIT : Intersect can not be used here as list1 items only contain a part of what's in list2 items.

A. Petit
  • 158
  • 3
  • 14
  • 2
    Possible duplicate of [Intersect LINQ query](https://stackoverflow.com/questions/2381049/intersect-linq-query) – Jules Nov 12 '19 at 09:08

2 Answers2

2

You can get the desired result by running Select over your first list, and then find the matching elements in the second lists, finally discarding the elements from the first list that have no match. This way, the elements generated come from the second list, but the structure of the list matches that of the first list:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{

    private static List<string> CompareLists2(List<string> list1, List<string> list2)
    {
        List<string> commonList = list1
           .Select(l1 => list2.FirstOrDefault(l2 => l2.Contains(l1)))
           .Where(x => x != null)
           .ToList();
        return commonList;
    }  


    public static void Main()
    {
        var list2 = new List<string> { "/folder/foo", "/folder/bar", "/folder/baz" }; 
        var list1 = new List<string> { "bar", "baz", "baz" };

        var result = CompareLists2(list1,list2);
        // result is { "/folder/bar", "/folder/baz", "/folder/baz" }
    }
}
Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
0

Use Enumerable.Intersect method

List<string> commonList = list1.Intersect(list2).ToList();

Try It

Bibin
  • 492
  • 5
  • 11