Intersect Two Lists in C#

Intersect Two Lists in C#

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Select(i => i.ToString()).Intersect(data2);


Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
// All data2 strings are int's
}

Intersection of two lists using LINQ

EDIT:
People in the comments are taking about overriding equals for your Company object and they are correct however we might be able to do something easier. The reason you need to override equals is because .Net doesn't know how to find equality in an object you created. so you would need to program in how to let it know. It does know how to find equality in an ID most times however.

EDIT 2:
The Intersect Any is the way to go because you are want to compare a list to a list

public List<User> GetUsers(User admin)
{
var adminCompanyIDs = admin.Companys.Select(c => c.ID);
return Users.Where(user=>user.Companys.Select(c => c.ID).Intersect(adminCompanyIDs).Any()).ToList();
}

So Contains will search the list to see if any single value are in the list. Because it only searches for a single value it won't work for this.

Intersect will return the intersections of the two lists. for example [1,2,3] [2,3,4] would give [2,3].

Where requires a boolean for the function evaluation. Give me the values in my list where the function given returns true. So when you give back [2,3] it complains. Any says are there any results in the list. so [2,3].Any() returns true, satisfying the Where.

Contains doesn't return the Intersection of the list, just tells you True of False, Does the value exist

Hope that helps.

Intersect two List in C#

Intersect<T> returns an IEnumerable<T>, so the correct way is:

var loads = l1.Intersect(l2).ToList();

ToList<T> creates a List<T> from an IEnumerable<T>.

Note that you can omit the type argument when invoking Intersect<T>, the compiler is smart enough to infer it.

intersect two lists with same object but diffrent variables

You can either override Equals (and GetHashCode) on ObjA to define "equality" as "having the same name", create a class that implements IEqualityComparer<ObjA> using the same rules, or just use a different Linq query:

List<ObjA> intersect = list1.Where(x => list2.Any(y => y.name == x.Name)).ToList();

Intersect two arrays

There's the Intersect extension method on Enumerable. It works on any IEnumerable<T> including arrays.

Joining two lists together

You could try:

List<string> a = new List<string>();
List<string> b = new List<string>();

a.AddRange(b);

MSDN page for AddRange

This preserves the order of the lists, but it doesn't remove any duplicates which Union would do.

This does change list a. If you wanted to preserve the original lists then you should use Concat (as pointed out in the other answers):

var newList = a.Concat(b);

This returns an IEnumerable as long as a is not null.

Intersection of two lists with repetitions

Map one of the sequences to a dictionary of items to the count of times they appear, then for each item in the other sequence, if it's in the collection, and the value of the lookup is greater than zero, yield it and decriment:

public static IEnumerable<T> IntersectWithRepetitons<T>(this IEnumerable<T> first,
IEnumerable<T> second)
{
var lookup = second.GroupBy(x => x)
.ToDictionary(group => group.Key, group => group.Count());
foreach (var item in first)
if (lookup.ContainsKey(item) && lookup[item] > 0)
{
yield return item;
lookup[item]--;
}
}

This ensures that items are yields for each time they are duplicated in both sets.

You could use TryGetValue to remove a few dictionary lookups, but it sacrifices a lot of the method's elegance, so I just didn't have it in me to do that. If you care about performance, it's not a bad thing to change.

intersect two lists with different objects

The general idea is

var commonUsers = list1.Select(a => a.User).Intersect(list2.Select(b => b.User));

However, by itself this assumes that User implements IEquatable<User>, which does not seem to be the case here. So you either need to add this implementation or use the Intersect overload that accepts a custom IEqualityComparer<User>.

Intersection of multiple lists with IEnumerable.Intersect()

How about:

var intersection = listOfLists
.Skip(1)
.Aggregate(
new HashSet<T>(listOfLists.First()),
(h, e) => { h.IntersectWith(e); return h; }
);

That way it's optimized by using the same HashSet throughout and still in a single statement. Just make sure that the listOfLists always contains at least one list.



Related Topics



Leave a reply



Submit