2012-05-10 44 views
0

我有一个包含列表(List<b>)的列表(List<a>)。 b型列表中有一个字符串字段。我想通过搜索列表a找到列表b中匹配字符串的索引。我怎样才能做到这一点?在C#中的列表中搜索

public class b 
{ 
    string Word; 
    bool Flag; 
} 

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

我想查找列表b中与字符串“Word”匹配的索引。

回答

2

这LINQ表达式返回BList和适当的瑶池指数的列表:

 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) 
     }); 
+0

这是一个非常好的方法,我认为但编译器给出错误:错误无效的匿名类型成员声明。匿名类型成员必须声明为成员分配,简单名称或成员访问权限。 – sanchop22

+0

FindIndex只返回第一个索引。 –

+0

好吧,我忘了给会员分配姓名,代码已更新。 –

1

是你需要什么?

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}); 
0

我想这取决于你想作为一个输出什么 - 这会给你喜欢的投影:

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) 
    }); 
0

这给你的所有对象巫婆满足您的“字”:

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