如何通过在C#中通过Lambda表达式将元组的一项与另一项列表匹配来过滤元组列表?

时间:2019-05-23 16:36:56

标签: c# lambda

我有一个元组列表:

List<Tuple<string, string>> keys = { ("AB","12"), ("BC","23"), ("XY","00")}

我还有另一个可枚举的字符串集合:

IEnumerable<string> results = {"ABC", "BCD", "ZZXY"}

我正在尝试编写一个lambda表达式,该表达式将为我提供所有键的列表,以便有一个以results开头的对应结果(在keys.item1列表中)。

所以最后,我想要以下内容:

List<Tuple<string, string>> finalKeys = { ("AB","12"), ("BC","23") }

2 个答案:

答案 0 :(得分:0)

使用Where语句和相应的Any调用:

List<Tuple<string, string>> finalKeys = keys
    .Where(key => results.Any(result => result.StartsWith(key.Item1)))
    .ToList();

答案 1 :(得分:0)

尝试:

         List<Tuple<string, string>> keys = new List<Tuple<string, string>>
         {
            new Tuple<string, string>("AB", "12"),
            new Tuple<string, string>("BC", "23"),
            new Tuple<string, string>("XY", "00")
         };

         IEnumerable<string> results = new List<string> {"ABC", "BCD", "ZZXY"};

         var finalKeys = keys.Where(f => results.Any(m => m.StartsWith(f.Item1))).ToList();