【问题标题】:C#: 'IEnumerable<Student>' does not contain a definition for 'Intersect'C#:“IEnumerable<Student>”不包含“Intersect”的定义
【发布时间】:2016-12-10 02:55:59
【问题描述】:

我已经很久没有写过一行代码了,如果我问的是一个愚蠢的问题,请耐心等待。

即使 IntelliSense 在 Names 之后显示 Intersect 方法,尝试比较两个 IEnumerables 时仍会出现以下错误。

我正在尝试将数据库查询的结果与 html 中的有序列表进行比较。

“IEnumerable”不包含“Intersect”的定义和最佳扩展方法重载 'Queryable.Intersect(IQueryable, IEnumerable)' 需要接收器类型 '可查询'

namespace Data.Repositories
{
    public class StudentsRepository
    {
        public class Student
        { 
            public string FullName { get; set; }
        }

        public static IEnumerable<Student> GetData(string CardNumber, string Section)
        {
            // FullName varchar(300) in Database
            return CommonFunctions.ExecuteReader1<Student>(QryStudentSectionDetails(CardNumber, Section)).AsQueryable();
        }
    }
}


namespace Tests.ActionsLibrary.StudentPaper
{
    public class StudentActions:TestBase
    {
        bool IsMatch = false;

        // Get Names from DataBase
        IEnumerable<Student> Names = GetData(CardNumber, Section);

        // Get Names from Ordered list in HTML
        IEnumerable<IWebElement> OrderedList = driver.FindElements(By.XPath("//li[@ng-repeat='Names']"));

        if (Names.Count() == OrderedList.Count() && Names.Intersect(OrderedList).Count() == OrderedList.Count()) // The error is shown here.
        { IsMatch = true; }

我想知道我做错了什么。任何帮助将不胜感激。谢谢。

最后代码如下:

    IEnumerable<string> Names = GetData(CardNumber, Section).Select(s => s.FullName);
    IEnumerable<string> OrderedList = driver.FindElements(By.XPath("//li[@ng-repeat='Names']")).Select(i => i.Text);

非常感谢您的帮助。

【问题讨论】:

  • 你认为它会在StudentsIWebElements 之间相交吗?除此之外,您可能还有其他问题,但这确实是您可能应该注意的问题。

标签: c# linq ienumerable generic-collections


【解决方案1】:

这是因为Intersect 要求两个集合的类型相同。您正在尝试使用集合或StudentIWebElement 的集合来调用它。

在调用Intersect 或使用不同的方法来完成任务之前,请确保您有两个相同类型的集合。

您可以将两个集合都投影到可以轻松比较的东西中(例如IEnumerable&lt;string&gt;):

var studentNames = Names.Select(student => student.Name);
var webElementNames = OrderedList.Select(webElement => webElement.Name);

或者您可以使用All 这样做:

if(Names.All(student => OrderedList.Any(webElement => webElement.Name == student.Name)))

我不知道你想比较什么属性,所以用有意义的东西替换谓词。

【讨论】:

  • 工作就像一个魅力。谢谢!
猜你喜欢
  • 2018-05-21
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多