Returns the index of sublist in the given IList. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Returns the index of sublist in the given IList.

Demo Code

/*/* w  w w .  j av  a  2 s.c  o m*/
    Copyright (C) 2007-2017 Team MediaPortal
    http://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MediaPortal 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        /// <summary>
    /// Returns the index of <paramref name="subList"/> in the given <paramref name="list"/>.
    /// </summary>
    /// <param name="list">List to search through.</param>
    /// <param name="subList">Sublist to find.</param>
    /// <param name="comparer">Comparer to compare elements.</param>
    /// <returns>Index of the sub sequence, if it is present or <c>-1</c> if not.</returns>
    public static int IndexOf<S, T>(IList<S> list, IList<T> subList, IEqualityComparer<S> comparer)
        where T : class, S
    {
      for (int i = 0; i < list.Count - subList.Count + 1; i++)
      {
        bool allEqual = true;
        for (int j = 0; j < subList.Count; j++)
          if (!comparer.Equals(list[i + j], subList[j]))
          {
            allEqual = false;
            break;
          }
        if (allEqual)
          return i;
      }
      return -1;
    }
        /// <summary>
    /// Returns the index of <paramref name="subList"/> in the given <paramref name="list"/>.
    /// </summary>
    /// <param name="list">List to search through.</param>
    /// <param name="subList">Sublist to find.</param>
    /// <returns>Index of the sub sequence, if it is present or <c>-1</c> if not.</returns>
    public static int IndexOf<T>(IList<T> list, IList<T> subList) where T : IEqualityComparer<T>
    {
      for (int i = 0; i < list.Count - subList.Count + 1; i++)
      {
        bool allEqual = true;
        for (int j = 0; j < subList.Count; j++)
          if (!list[i + j].Equals(subList[j]))
          {
            allEqual = false;
            break;
          }
        if (allEqual)
          return i;
      }
      return -1;
    }
}

Related Tutorials