How to merge 2 ListT and removing duplicate values from it in C#
Have you had a look at Enumerable.Union
This method excludes duplicates from the return set. This is different
behavior to the Concat
method, which returns all the elements
in the input sequences including
duplicates.
List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();
// ulist output : 1, 12, 5, 7, 9
How to merge two lists and remove duplicates
Try the Union extension method.
var result = listA.Union(listB).ToList();
Union produces the set union of two sequences by using the default equality comparer so the result contains only distinct values from both lists.
Combining 2 lists and and remove duplicates .Output in a third list .My attempts do not work
The crux of the problem is the Customer object doesn't have a .Equals() implementation. If you override .Equals (and .GetHashCode) then .Distinct would use it to eliminate duplicates. If you don't own the Customer implementation, however, adding .Equals may not be an option.
An alternative is to pass a custom IEqualityComparer to .Distinct(). This lets you compare objects in different ways depending on which comparer you pass in.
Another alternative is to GroupBy the fields that are important and take any item from the group (since the GroupBy acts as .Equals in this case). This requires the least code to be written.
e.g.
var result = listOne.Concat(listTwo)
.GroupBy(x=>x.Category+"|"+x.Name+"|"+x.Surname)
.Select(x=>x.First());
which gets your desired result.
Compare 2 lists of the same type and remove duplicates
See Enumerable.Union
in MSDN.
Create an IEqualityComparer
class:
class AdditionalInfoComparer : IEqualityComparer<ICrmCdsAdditionalInformation> {
public bool Equals(ICrmCdsAdditionalInformation x, ICrmCdsAdditionalInformation y) {
if (Object.ReferenceEquals(x, y))
return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.Code == y.Code;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(ICrmCdsAdditionalInformation info) {
if (Object.ReferenceEquals(info, null)) return 0;
return info.Code;
}
}
Then just,
var mergedList = list1.Union(list2, new AdditionalInfoComparer());
Remove duplicates from a ListT in C#
Perhaps you should consider using a HashSet.
From the MSDN link:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
Merge 2 List of Objects, no duplicates, based on comparison
First you need the common property in the interface, otherwise you can't use polymoprhism to access it when you enumerate the items in the List<IStuff>
:
interface IStuff
{
int ValueOfMyThing { get; set; }
}
Now add this property to the classes as well (omitted).
Then you could use this LINQ query to group by the concrete type, for example Car
, and get the item with the highest ValueOfMyThing
for each group:
List<IStuff> stuffList3 = stuffList1.Concat(stuffList2)
.GroupBy(x => x.GetType())
.Select(g => g.OrderByDescending(x => x.ValueOfMyThing).First())
.ToList();
This works, but I need stuffList3 to contain new Instances
Then you could provide a method to copy existing instances to new:
public interface IStuff
{
int ValueOfMyThing { get; set; }
IStuff Copy();
}
add it to your classes:
public class Toaster : IStuff
{
public int ValueOfMyThing { get; set; }
public IStuff Copy()
{
return new Toaster { ValueOfMyThing = ValueOfMyThing };
}
}
// ...
and call Copy
:
List<IStuff> stuffList3 = stuffList1.Concat(stuffList2)
.GroupBy(x => x.GetType())
.Select(g => g.OrderByDescending(x => x.ValueOfMyThing).First().Copy())
.ToList();
C# Merging duplicate list items and sum their second values (2D Object List)
Well, simple group by should work:
liste1
.GroupBy(x => x.Barcode)
.Select(g => new Product()
{
Barcode = g.Key,
Quantity = g.Select(x => x.Quantity).Sum()
});
Related Topics
How to Convert an Iso8601 Timespan to a C# Timespan
Identityserver4 Role Based Authorization for Web API with ASP.NET Core Identity
Query Extremely Slow in Code But Fast in Ssms
Should I Store My Images in the Database or Folders
How to Create CSV Excel File C#
Convert Bitmaps to One Multipage Tiff Image in .Net 2.0
Check If Instance Is of a Type
Creating a Temporary Directory in Windows
How to Get a Variable's Name as It Was Physically Typed in Its Declaration
Compare Nullable Types in Linq to SQL
Winforms | C# | Autocomplete in the Middle of a Textbox
Displaynamefor() from List<Object> in Model
Is There Any Way in C# to Override a Class Method with an Extension Method
How to List the Contents of a .Zip Folder in C#
Windows 7 and Vista Uac - Programmatically Requesting Elevation in C#