如何在列表中搜索给定项目列表是否以相同顺序存在

时间:2018-12-22 15:48:10

标签: c# linq

我需要使用LINQ来检查列表是否包含所有项,并且顺序是否相同,并且是否找到匹配项返回最后一个匹配元素。

var allWords = new List<string> { "A", "B", "C", "D", "E", "F"};
var words = new List<string>() { "D", "E" };

应返回元素“ E”(因为存在匹配项)

3 个答案:

答案 0 :(得分:3)

您可以使用Linq做到这一点。

var allWords = new List<string> { "A", "B", "C", "D", "E", "F","D", "E", "E"};
var words = new List<string>() {"D","E"  };
var indexOfLastOccuranceOfSequence = Enumerable.Range(0, allWords.Count - words.Count + 1)
        .Select(a => allWords.Skip(a).Take(words.Count)).ToList()
        .FindLastIndex(a => a.SequenceEqual(words));
var indexOfLastElement = indexOfLastOccuranceOfSequence+ words.Count() - 1;

答案 1 :(得分:2)

您可以在列表中找到第一个单词并对其进行迭代:

SELECT c.id AS courseid, c.fullname AS coursename,
    u.id AS userid, u.firstname, u.lastname,
    e.enrol AS enrolmethod, ue.timecreated AS timeenrolled,
    cc.timecompleted,
CASE
    WHEN cc.status = 10 THEN 'Not yet started'
    WHEN cc.status = 25 THEN 'In progress'
    WHEN cc.status = 50 THEN 'Completed'
    WHEN cc.status = 75 THEN 'Completed via Record of Prior Learning'
    ELSE 'Unknown'
END AS completionstatus
FROM mdl_course c
JOIN mdl_enrol e ON e.courseid = c.id
JOIN mdl_user_enrolments ue ON ue.enrolid = e.id
JOIN mdl_user u ON u.id = ue.userid
JOIN mdl_course_completions cc ON cc.course = c.id AND cc.userid = u.id

上面的程序返回FROM mdl_course c JOIN mdl_course_completions cc ON cc.course = c.id JOIN mdl_user u ON u.id = cc.userid LEFT JOIN ( SELECT ue.userid, e.courseid, MIN(ue.timecreated) AS timecreated FROM mdl_enrol e JOIN mdl_user_enrolments ue ON ue.enrolid = e.id GROUP BY ue.userid, e.courseid ) ue ON ue.userid = u.id AND ue.courseid = c.id 中最后一个匹配项的索引。要查找列表中单词的第一个出现,您可以查看this post

答案 2 :(得分:0)

您可以通过以下方式找到存在:

List<int> indexes = allWords.Where(x => words.Contains(x)).Select(x => allWords.IndexOf(x)).ToList();
if(indexes.Count() == words.Count())
{
    // then check indexes if SORTED, if so then they are in the same sequence
    return words.Last();  

}