C# - Linq with two Lists

c# compare two lists for matches linq
linq compare two lists for differences
c# linq join two lists
linq merge two different lists
linq where in list
linq contains list
c# compare two lists of different objects
find uncommon elements in two lists c#

I've got 2 classes which are connected together via an ID:

public class A {
    public int AID;
    public string Name;
}

public class B {
    public int BID;
    public int AID;
}

Now I want to filter my listB to get all B where A's Name is euqals the parameter name:

List<A> listA = ...;
List<B> listB = ...;

public List<B> Filter(string name) {
    var list = listB.Where(**... A.Name == name ...**).ToList();
    return list;
}

I don't know how to filter listB with the parameter I defined above. Maybe someone can help me figuring it out.

Thanks!

Although you could filter a list of Bs using b.AID linear search, it would be inefficient:

return listB.Where(b => listA.FirstOrDefault(a => a.AID == b.AID)?.Name == name);

A better approach would be to place entries from listA into a Dictionary<int,A>, and use dictionary lookup by b.AID:

IDictionary<int,A> dictA = listA.ToDictionary(a => a.AID);
return listB.Where(b => dictA.TryGetValue(b.AID, out var a) && a.Name == name);

I would highly recommend keeping As in dictA rather than listA, because it would let you avoid rebuilding the dictionary for each query.

How to find the set difference between two lists (LINQ) (C#), This example shows how to use LINQ to compare two lists of strings and output those lines that are in names1.txt but not in names2.txt. Some types of query operations in C#, such as Except, Distinct, Union, and Concat, can only be expressed in method-based syntax. Compiling the Code Create a C# console application project, with using directives for the System.Linq and System.IO namespaces.

Use Join and Where. I prefer the query syntax with joins:

IEnumerable<B> bs = 
    from a in listA
    join b in listB on a.AID equals b.AID
    where a.Name == name
    select b;
List<B> list = bs.ToList();

Another way which avoids duplicate B's (if it's a 1-to-many relationship) is using a lookup:

ILookup<int, string> aNameLookup = listA.ToLookup(a => a.AID, a => a.Name);
List<B> list = listB.Where(b => aNameLookup[b.AID].Contains(name)).ToList();

Perform inner joins (LINQ in C#), Hi, I have two lists of people i.e. List<Person>. I want to have a final list that will have each unique person from both list A and list B. A person  I have a C# application. I have two lists ('NewStock' and 'OldStock') of the same custom type, 'Book'. I want to extract any 'Book' object that is the list NewStock but not in the OldStock list int

try join like as below in linq

form b in listB 
join a in listA.Where(A.Name == name)
on a.AID equals b.AID
select b;

or get list of id first and then filter out

  var ids = from a in listA 
            where A.Name == name
            select a.AID;
  var Bs = from b in listB
            where ids.Contain(b.AID)
            select b;

How do I combine two lists using LINQ?, This post gives you the code to check if two lists contain a match. It is written in C# and uses LINQ. Linq inner join, left outer join on two lists in C# with example Linq inner join, left outer join on two lists in C# with example Joining two generic lists in linq is tricky, in this article we will see how we can join two lists by using inner join and then by using outer join.

use group join to avoid introducing duplication in listB.

var filteredA = listA.Where(a => a.Name == name);
var query =
  from b in listB
  join a in filteredA on b.AID equals a.AID into matchedAgroup
  where matchedAgroup.Any()
  select b;

LINQ method to see if two lists contain a match, New initialList list should include (Green and Yellow). static void Main(string[] args)  Any number of join operations can be appended to each other to perform a multiple join. Each join clause in C# correlates a specified data source with the results of the previous join. The following example creates three collections: a list of Person objects, a list of Cat objects, and a list of Dog objects.

I have used this in the past for a succinct subset list:

    public void TestGetListBMatchingListA()
    {
        List<ClassA> listClassA = new List<ClassA>();
        listClassA.Add(new ClassA { ClassAId = 1, Name = "JayV1" });
        listClassA.Add(new ClassA { ClassAId = 2, Name = "JayV2" });
        listClassA.Add(new ClassA { ClassAId = 3, Name = "JayV3" });
        listClassA.Add(new ClassA { ClassAId = 4, Name = "JayV4" });
        listClassA.Add(new ClassA { ClassAId = 5, Name = "JayV5" });

        List<ClassB> listClassB = new List<ClassB>();
        listClassB.Add(new ClassB { ClassBId = 1, ClassAId = 1 });
        listClassB.Add(new ClassB { ClassBId = 2, ClassAId = 2 });
        listClassB.Add(new ClassB { ClassBId = 3, ClassAId = 3 });
        listClassB.Add(new ClassB { ClassBId = 4, ClassAId = 4 });
        listClassB.Add(new ClassB { ClassBId = 5, ClassAId = 1 });
        listClassB.Add(new ClassB { ClassBId = 6, ClassAId = 2 });
        listClassB.Add(new ClassB { ClassBId = 7, ClassAId = 3 });
        listClassB.Add(new ClassB { ClassBId = 8, ClassAId = 4 });
        listClassB.Add(new ClassB { ClassBId = 9, ClassAId = 5 });
        listClassB.Add(new ClassB { ClassBId = 10, ClassAId = 1 });

        var result = listClassB.Where(classB =>
                                        listClassA.Any(classA =>
                                        classB.ClassAId == classA.ClassAId 
                                        && classA.Name == "JayV1")).ToList();

        result.ForEach(r => Debug.WriteLine(r.ClassBId));
    }

It produces the result of:

1
5
10

Using LINQ or Lambda instead of nested and multiple foreach , Here are two different ways of doing it: 1. Standard Query. Hide Copy Code. var resultantList = from item1 in list1 join item2 in list2 on item1. i want to compare the MsgID in Msglist with the sentlist and need items which are not in the sent list using linq Result MsgID Content 2 bbb 4 ddd 5 eee c# linq list c#-4.0

C#LINQ lambda -to get data comparing fields from two lists , Hide Copy Code. Common = NewClient.Where(n => oldClient.Any(o => o.​ClientID == n.ClientID)).ToList(); Deleted = oldClient.Where(o => ! Merge two lists by id and select the item of with a max value Tag: c#, linq I have two lists of Level, and I want to merge them into a single list with only unique indexes, and having the higher highscore of the two.

Difference between two list<object> linq, Compare two List objects for equality, with regard to order. If ordering of elements matters, we can simply use LINQ's SequenceEqual() method which determines  C# Join Two Lists Together. In C for adding a list to another list, can be used addRange or Concat method. You can concatenate Lists in C# by following ways. AddRange: Adds the elements of the specified collection to the end of the List<T>. Example 1: Can be used this code joining two lists together.

Compare two Lists for equality, ignoring order in C#, For better understanding, we will use an example. First, we will go with a simple example, for that I created two lists. List<  Write LINQ queries in C#. 12/01/2016; 4 minutes to read +3; In this article. This article shows the three ways in which you can write a LINQ query in C#: Use query syntax. Use method syntax. Use a combination of query syntax and method syntax. The following examples demonstrate some simple LINQ queries by using each approach listed previously.

Comments
  • unclear and confusing, an example may help us to identify what exactly you are asking
  • This is exactly i was looking for, especially it was written the way I need it to be! Thank you a lot!!!
  • @DanielDirtyNativeMartin: edited my answer to provide another approach using a lookup. That' s similar to this second approach with the dictionary but avoids an error if there are multiple A with the same ID and works also if there is no A with that ID(without TryGetValue).
  • Depends on the size. On (very) small lists, search is more efficient than on a dictionary
  • wouldnt be it better if we filter listA fist ?
  • @PranayRana: No, this is more efficient and joins filter as well
  • Okies ... no problem
  • Note: join can introduce duplication.
  • @AmyB: True, so if that is possible and not desired he could use bs.Distinct().ToList()