sanchop22
sanchop22

Reputation: 2809

Search in List of List in C#

I have a list (List<a>) that contains a list (List<b>). There is a string field in b type list. I want to to find the indexes of matching strings in list b by searching list a. How can i do that?

public class b
{
    string Word;
    bool Flag;
}

public class a
{
    List<b> BList = new List<b>();
    int Counter;
}

I want to find indexes in list b that matches with the string "Word".

Upvotes: 0

Views: 445

Answers (4)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4908

This Linq Expression return a List of BList and proper finded Index:

        var Result = AList.Select(p => new
        {
            BList = p.BList,
            indexes = p.BList.Select((q, i) => new
            {
                index = i,
                isMatch = q.Word == "Word"
            }
            )
            .Where(q => q.isMatch)
            .Select(q=>q.index)
        });

Upvotes: 2

Dave Bish
Dave Bish

Reputation: 19656

I guess this depends on what you want as an output - this will give you a projection like:

indexes[0] { A = A[0], Indexes = {1,5,6,7} }
indexes[1] { A = A[1], Indexes = {4,5,8} }
...

var indexes = listA
    .Select(a => new 
    { 
        A = a, 
        Indexes = a.BList
            .Select((b, idx) => b == wordToCheck ? idx : -1)
            .Where(i => i > -1)
    });

Upvotes: 0

webber2k6
webber2k6

Reputation: 648

this gives you all objects witch meet your 'word':

from a in aList from b in a.bList where b.word.Equals("word") select b;

Upvotes: 0

ie.
ie.

Reputation: 6101

Is that what you need?

var alist = GetListA();

var indexes = alist.Select((ix, a) => 
                           a.BList.SelectMany((jx, b) => 
                                              new {AIx = ix, BIx = jx, b.Word}))
                   .Where(x => x.Word == pattern)
                   .Select(x => new {x.AIx, x.BIx});

Upvotes: 1

Related Questions