Q:

Clean duplicates and their instances from a list

I have a datamodel like this :
    public class AmpFile
    {
        public string filename { get; set; }
        public string actualpath { get; set; }
    }

Now I have a list of it like this :
[ list member 1 ]    -    filename:  "testfile1.jpg"    -    actualpath:  "C:\testpath\testfile1.jpg" 
[ list member 2 ]    -    filename:  "brickwall.jpg"    -    actualpath:  "C:\testpath\brickwall.jpg" 
[ list member 3 ]    -    filename:  "mydata.txt"    -    actualpath:  "D:\mydata.txt" 
[ list member 4 ]    -    filename:  "testfile1.jpg"    -    actualpath:  "E:\demo\testfile1.jpg" 
[ list member 5 ]    -    filename:  "mydata.txt"    -    actualpath:  "F:\somefolder\mydata.txt" 
[ list member 6 ]    -    filename:  "testfile1.jpg"    -    actualpath:  "F:\somefolder\testfile1.jpg" 
[ list member 7 ]    -    filename:  "testfile2.jpg"    -    actualpath:  "F:\somefolder\testfile2.jpg" 
[ list member 7 ]    -    filename:  "testfile3.jpg"    -    actualpath:  "D:\testfile3.jpg" 

Now I want to find duplicates of each member and if there's a duplicate of it , I want to remove duplicates + the reference itself so the result I want to achieve is :
[ list member 1 ]    -    filename:  "brickwall.jpg"    -    actualpath:  "C:\testpath\brickwall.jpg" 
[ list member 2 ]    -    filename:  "testfile2.jpg"    -    actualpath:  "F:\somefolder\testfile2.jpg" 
[ list member 3 ]    -    filename:  "testfile3.jpg"    -    actualpath:  "D:\testfile3.jpg" 

How can I do it ?

A:

you can do it with Linq, by using Group by and filter all elements that have count == 1, like the following code:
1 - Prepare list of ampFile:
List<AmpFile> ampFiles = new List<AmpFile>
{
    new AmpFile{filename="testfile1.jpg",actualpath="C:\\testpath\\testfile1.jpg"},
    new AmpFile{filename="brickwall.jpg",actualpath="C:\\testpath\\brickwall.jpg"},
    new AmpFile{filename="mydata.txt",actualpath="D:\\mydata.txt"},
    new AmpFile{filename="testfile1.jpg",actualpath="E:\\demo\testfile1.jpg"},
    new AmpFile{filename="mydata.txt",actualpath="F:\\somefolder\\mydata.txt"},
    new AmpFile{filename="testfile1.jpg",actualpath="F:\\somefolder\\testfile1.jpg"},
    new AmpFile{filename="testfile2.jpg",actualpath="F:\\somefolder\\testfile2.jpg"},
    new AmpFile{filename="testfile3.jpg",actualpath="D:\\testfile3.jpg"},
};

2 - Call groupBy and filter with Where:
List<AmpFile> notDuplicatedAmpFiles = ampFiles.GroupBy(x => x.filename)
    .Where(x => x.Count() == 1)
    .SelectMany(x => x)
    .ToList();

3 - Demo:
foreach(AmpFile ampFile in notDuplicatedAmpFiles)
{
    Console.WriteLine($"fileName :{ampFile.filename}, actualPath :{ampFile.actualpath}");
}

4 - Result:
fileName :brickwall.jpg, actualPath :C:\testpath\brickwall.jpg
fileName :testfile2.jpg, actualPath :F:\somefolder\testfile2.jpg
fileName :testfile3.jpg, actualPath :D:\testfile3.jpg

I hope this help.

