Linq条件“where id = List <item> newList”如何实现</item>

时间:2013-03-22 02:46:34

标签: c# linq

List<string>resultList=new List<string>();
List<string>allID=new List<string>();
allID.Add("a1");
allID.Add("a2");
allID.Add("a3");
allID.Add("a4");
allID.Add("a5");
allID.Add("a6");
List<string>selectedID=new List<string>();
selectedID.Add("1");
selectedID.Add("3");
selectedID.Add("5");
resultList=(from a in allID where a.Contains(**one of the ID form selectedID**) select a).ToList();

能告诉我工作版吗?

4 个答案:

答案 0 :(得分:2)

如果您想检查每个a是否与selectedID内的条目完全匹配,请使用:

(from a in allID where selectedID.Contains(a) select a).ToList()

这不会返回与您的示例代码匹配的任何内容。


如果您想检查每个字符串a是否包含selectedID任何条目的内容,请使用:

(from a in allID
 where selectedID.Any(s => a.Contains(s))
 select a).ToList()

这将返回{ "a1", "a3", "a5" }

答案 1 :(得分:1)

我认为你要做的是:

resultList = 
    (from a in allID 
     where selectedID.Any(s => ("a" + s) == a)
     select a)
    .ToList();

它将返回allIDselectedID中的{{1}}项(进行一些格式调整)。

答案 2 :(得分:1)

resultList = allID.Where(x => selectedID.Select(s => "a" + s).Contains(x))
                  .ToList<string>();

答案 3 :(得分:0)

还有一个。 Linq很酷:))

检查allID是否包含selectedID

中任何条目的内容
resultList = allID.Where(all => selectedID.Any(select => all.Contains(select))).ToList();

resultList将包含{“a1”,“a3”,“a5”}

相关问题