Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在仅使用LINQ的情况下使用IEquatable比较两个集合_C#_Linq_.net 4.5_Ienumerable_Iequatable - Fatal编程技术网

C# 在仅使用LINQ的情况下使用IEquatable比较两个集合

C# 在仅使用LINQ的情况下使用IEquatable比较两个集合,c#,linq,.net-4.5,ienumerable,iequatable,C#,Linq,.net 4.5,Ienumerable,Iequatable,这个问题仅用于教育目的,我可以通过使用for循环轻松解决它,该循环在第一次不匹配时返回false 我正在CustomerFeedbackViewModel上实现IEquatable,它有一个QuestionViewModel集合,我需要逐个元素进行比较 public class CustomerFeedbackViewModel { public List<QuestionViewModel> Questions { get; set; } public stri

这个问题仅用于教育目的,我可以通过使用
for
循环轻松解决它,该循环在第一次不匹配时返回
false

我正在
CustomerFeedbackViewModel
上实现
IEquatable
,它有一个
QuestionViewModel
集合,我需要逐个元素进行比较

public class CustomerFeedbackViewModel 
{
    public List<QuestionViewModel> Questions { get; set; }

    public string PageName { get; set; }

    public string SessionId { get; set; }
}
Ofc
TrueForAll
没有索引,上面的内容永远不会飞行


如果不使用
for
循环,而是使用linq'oneliner',我如何实现两个列表的比较?

而不是在您应该使用的所有索引上比较每个问题:


如果您不在
QuestionViewModel
中覆盖
Equals
+
GethashCode
,您可以提供一个自定义值并将其传递给
SequenceEqual
重载或实现
IEquatable

我想您需要
列表1.SequenceEqual(列表2.Take(列表1.Count))
将列表1中的所有元素与列表2中的相应元素进行比较。嗨,Tim,没有更好的解决方案了,谢谢:)我刚刚意识到我将继续重写spree,以更改我用于循环的所有位置。如果不使用.NET Core,可能值得测试的是,这两个序列具有相同的计数,否则将成为false的捷径。如果序列都实现了
ICollection
并具有不同的计数,那么NET Core将成为捷径,但其他框架版本的
SequenceEqual
则不会。
public bool Equals(CustomerFeedbackViewModel other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return Questions.TrueForAll((o,i) => o.Equals(other.Questions.ElementAt(i))) && string.Equals(PageName, other.PageName) && string.Equals(SessionId, other.SessionId);
    }
return string.Equals(PageName, other.PageName) 
    && string.Equals(SessionId, other.SessionId) 
    && Questions.SequenceEqual(other.Questions);