Kazooo
Kazooo

Reputation: 1

Find elements in one list based on content in another list

How is it possible by use of LINQ to get elements from one list based on another list. I have two lists: List lstA and List lstB

pseudo declarations:

public class A
{
string strTag;
int iCounter;
string strInfo;
}

public class B
{
string strTag;
int iIndex;
DateTime? dtTimeStamp;
string strCustomerID,
string strCustomerName;
}

Both lists contains the strTag element. I would like to collect the elements from lstB where the strTag element is included in lstA.

I was thinking of something like

var newList = 
from t in lstB 
join s in lstA on t.strTag equals s.strTag into TempData
from r in TempData select r;

For clarification: lstB contains thousands of records and lstA contains 1-25 records. I need the 1-25 records from lstB where the strTag match the strTag in a record in lstA

Upvotes: 0

Views: 122

Answers (5)

Nacho
Nacho

Reputation: 962

Try this

lstA.Join(lstB, a => a.strTag, b => b.strTag, (a, b) => b);

Upvotes: 0

Kazooo
Kazooo

Reputation: 1

Actually there was no problem at all with joining the lists. The problems was that in one of the lists a blank character was inserted in the end of the strTag.

Thanks for your suggestions. I have tried many of them which also gives the correct result when the blank character is removed.

Upvotes: 0

SelvaS
SelvaS

Reputation: 2125

You have to get strTag in a list and use Contains to filter out matched records. Try something like this,

        List<A> lstA = new List<A>();
        List<B> lstB = new List<B>();
        List<string> strTagsinA = lstA.Select(x => x.strTag).ToList();

        var result = (from b in lstB
                 where strTagsinA.Contains(b.strTag)
                 select b).ToList();

Upvotes: 0

EagleBeak
EagleBeak

Reputation: 7419

A combination of Where() and Contains() should do the trick:

var listA = new[]{"1", "2", "3"}.Select(s => new A{strTag = s});

var r = new Random();

//list of 100 items containing random values between "1" and "100" for strTag 
var listB = Enumerable.Range(1,100).Select(i => new B{ strTag =r.Next(1,11).ToString()});

var filtered = listB.Where(b => listA.Select(a => a.strTag).Contains(b.strTag));

Upvotes: 0

Florian Schmidinger
Florian Schmidinger

Reputation: 4692

I'd implement it using an anonymous type:

var newList = from t in lstB
              join s in lstA on t.strTag equals s.strTag 
              select new {B = t, A = s};

Upvotes: 1

Related Questions