0

是否可以使用 LINQ 测试列表项序列的匹配?例如

var masterList = new List<string>{"fox", "jumps", "dog"};
var childList1 = new List<string>{"fox", "jumps"};
var childList2 = new List<string>{"fox", "dog"};

我想写一些东西,以便在 masterList 中寻找 childList1 是真的,但 childList2 是假的,因为介于两者之间。

编辑: {"jumps", "dog"} 也会匹配。

4

3 回答 3

1

如果元素的确切顺序很重要,请尝试以下操作:

public static bool ListContains<T>(List<T> source, List<T> search)
{
    if (search.Count > source.Count)
        return false;

    return Enumerable.Range(0, source.Count - search.Count + 1)
        .Select(a => source.Skip(a).Take(search.Count))
        .Any(a => a.SequenceEqual(search));
}

public static void Main(string[] args)
{
    var masterList = new List<string> { "fox", "jumps", "dog" };
    var childList1 = new List<string> { "fox", "jumps" };
    var childList2 = new List<string> { "fox", "dog" };

    Console.WriteLine(ListContains(masterList, childList1));
    Console.WriteLine(ListContains(masterList, childList2));
}
于 2013-09-06T21:43:44.880 回答
1

我的答案与 Andrei 的相似,但可能更快,因为它会在父列表中查找第一项以限制搜索次数:

public bool SubsequenceEquals<T>(IEnumerable<T> masterList, IEnumerable<T> childList)
{
    // find all indexes 
    var matches = masterList.Select((s, i) => new {s, i})
                            .Where(m => m.s.Equals(childList.First()))
                            .Select (m => m.i);

    return matches.Any(m => Enumerable.SequenceEqual(childList, masterList
                                                           .Skip(m)
                                                           .Take(childList.Count())));
}
于 2013-09-06T21:53:42.793 回答
0

还有另一个问题有一个有效的答案;检查一个数组是否是另一个数组的子集

bool isSubest = !childList1.Except(masterList).Any();

会为你做的。你也可以做

  if (childList1.Except(masterList).Count > 0)
      // items in child not in master
  else
       //child is a subest of master
于 2013-09-06T21:37:31.183 回答