English 中文(简体)
LINQ 列表包含另一个列表( 相近)
原标题:LINQ List Contains Another List (Contiguous)

我找不到一个有效但简单的方法来检查列表是否包含另一个列表( 保留顺序) 。 它类似于字符串。 Contains( string) 功能 。

说我有四个集注:

 A = [1, 2, 3, 4, 5]
 B = [2, 3]
 C = [5, 6, 7]
 D = [3, 2, 4]

A. contains(B) 将是真实的,而 A. contains(C) A. contains(D) 将是虚假的。

如果有帮助,我宁可不使用迭代器,但我无法想象一个有效的方法来做到这一点;以下的代码效率极低。

 public static bool IsSequentiallyEqual<T>(this IEnumerable<T> lhs, IEnumerable<T> rhs)
 {
      return lhs.Zip(rhs, (a, b) => a.Equals(b)).All(isEqual => isEqual == true);
 }

 public static bool StartsWith<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
 {
      return haystack.Take(needle.Count()).IsSequentiallyEqual(needle);
 }

 public static bool Contains<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
 {
      var result = list.SkipWhile((ele, index) => haystack.Skip(index).StartsWith(needle));
      return result.Count() >= needle.Count();
 }
最佳回答
public static bool Contains<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
{
    var hayList = haystack.ToList();
    var needleList = needle.ToList();
    return Enumerable.Range(0, hayList.Count)
                     .Select(start => hayList.Skip(start).Take(needleList.Count))
                     .Any( subsequence => subsequence.SequenceEqual(needleList));
}
问题回答
public static bool Contains<T>(this IEnumerable<T> first, IEnumerable<T> second)
 {
      return string.Join("~", first).Contains(string.Join("~", second));
 }

至少避免长长长名单中的工作。

public static bool Contains<T>(this IEnumerable<T> first, IEnumerable<T> second)
   {
       //trying to avoid multiple enumeration
        var firstList = first.ToList();
        var secondList = second.ToList();

        if (!secondList.Any(firstList.Contains)) return false;
        if (secondList.Count() > firstList.Count()) return false;
        if (Math.Max(firstList.Count(), secondList.Count()) > 99999)
             throw new ShouldNotUseThisUglyMethodException("I m too kludgy to be used. Let me die...");
        return string.Join("~", firstList).Contains(string.Join("~", secondList));
    }

此版本使用队列来存储可能的子序列。 它只通过 < code> haystack 进行迭代, 仅一次从初始 < code> takee () < () 开始, 一旦发现匹配, 它就会停止迭代 。 但是, 它会在 LINQ 语句中变异变量 。

public static bool Contains<T>(this IEnumerable<T> haystack, IEnumerable<T> needle)
{
    var needleList = needle.ToList();
    var queue = new Queue<T>(haystack.Take(needleList.Count - 1));
    return haystack.Skip(needleList.Count - 1)
                   .Any( hay =>   
                       {
                           queue.Enqueue(hay);
                           bool areEqual = queue.SequenceEqual(needleList);
                           queue.Dequeue();
                           return areEqual;
                       });  
}

使用 hashes 的工作 。 请注意, 有一些检查可以立即返回假的, 但我只显示过程的肉类 。 这里使用的扩展格式 :

更新到处理顺序

void Main()
{
    var first        = new List<int>() { 1, 2, 5 };
    var firstInOrder = new List<int>() { 1, 2, 3 };
    var second       = new List<int>() { 1, 2, 3, 4, 5 };
    var third        = new List<int>() { 1, 10, 20 };

    Console.WriteLine( first.FoundInOther( second ) );        // False
    Console.WriteLine( firstInOrder.FoundInOther( second ) ); // True
    Console.WriteLine( first.FoundInOther( third ) );         // False

}

public static class NumberExtensions
{

    public static bool FoundInOther( this IEnumerable<int> initial, IEnumerable<int> other )
    {
        int index = -1;
        var asDictionary = other.ToDictionary( itm => itm, itm => ++index );

        index = -1;
        return initial.All( oth => asDictionary.ContainsKey( oth ) && (asDictionary[oth] == ++index));
    }

}




相关问题
IEnumerable to array of parameter

Using linq? and XML is there a way to convert this IEnumerable to a string array of the value parameter? List<string> idList = new List<string>(); foreach (XElement idElement in word....

linq query for tag system - search for multiple tags

I have two tables, Tags(tagid, postid, tagname) and posts(postid, name, ...) now i want to make a query that returns me all posts that have a generic amount of tags. like: i want all posts that have ...

Linq operations against a List of Hashtables?

I m working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

How to filter duplicate list items

i have list of items IList with data that looks list this: GenId TestMode 1 0 1 1 3 0 3 1 4 NULL 2 NULL i want to remove the index ...

C# Grouping/Sorting a Generic List<> using LINQ

Im looking to group and sort a Generic List<>. I have a list of objects representing files and each of these objects has a FileName, FileType and FileDate property. FileType is defined as an ...

热门标签