C# 我做了一个实践项目,需要比较两个列表。我如何进行比较?
我没有很好地解释它的逻辑 我有一张空名单:C# 我做了一个实践项目,需要比较两个列表。我如何进行比较?,c#,.net,C#,.net,我没有很好地解释它的逻辑 我有一张空名单: if (!newValues.Contains(myValues[i])) { newValues.Add(myValues[i]); } 那么这个方法: class NewsLine { public string text; public string time; public string link; } 您需要在第一个列表上循环以确保添加了所有项目: class NewsLine { public
if (!newValues.Contains(myValues[i]))
{
newValues.Add(myValues[i]);
}
那么这个方法:
class NewsLine
{
public string text;
public string time;
public string link;
}
您需要在第一个列表上循环以确保添加了所有项目:
class NewsLine
{
public string text;
public string original_time;
public string link;
// Straight compare of the two objects.
public static int Compare(NewsLine n1, NewsLine n2)
{
// How to do the comparisdon is up to you.
// In this example, if the first property is different we use that,
// else if the second property is different use that, else use the final property.
if (n1.text != n2.text)
return string.Compare(n1.text, n2.text);
else if (n1.original_time != n2.original_time)
return string.Compare(n1.original_time, n2.original_time);
else
return string.Compare(n1.link, n2.link);
}
这也可以使用LINQ完成:
foreach(int existingValue in myValues)
{
if(!newValues.Contains(existingValue))
{
newValues.Add(existingValue);
}
}
如果我理解正确,你可以这样做。 这将从existingValue中添加newValues中不存在的任何项
newValues.AddRange(myValues.Where(n => !newValues.Contains(n)));
创建一个nit测试,使用
CollectionAssert.AreEqual()
如果它们需要相同的顺序,CollectionAssert.areequivalent()
就是它们只需要包含相同的项。在我的问题中添加了更多的代码来解释更多的逻辑。这不仅仅是为了比较,更重要的是检查新的数字/项目,并决定是否将它们添加到新列表中。由于您更改了您要查找的内容,它会更改已发布的答案,但我很难从更新的帖子中准确理解您想要做什么。为什么您需要一份表格
,答案由Tsukasa应该能解决你的问题。上次我知道这是错误的,我更新了我的问题,但我得到的答案是我的意思,但我仍然不明白它是如何工作的,所以我用数字做了一个项目,但我添加的最后一部分是我的意思。
class NewsLine
{
public string text;
public string original_time;
public string link;
// Straight compare of the two objects.
public static int Compare(NewsLine n1, NewsLine n2)
{
// How to do the comparisdon is up to you.
// In this example, if the first property is different we use that,
// else if the second property is different use that, else use the final property.
if (n1.text != n2.text)
return string.Compare(n1.text, n2.text);
else if (n1.original_time != n2.original_time)
return string.Compare(n1.original_time, n2.original_time);
else
return string.Compare(n1.link, n2.link);
}
foreach(int existingValue in myValues)
{
if(!newValues.Contains(existingValue))
{
newValues.Add(existingValue);
}
}
newValues.AddRange(myValues.Where(n => !newValues.Contains(n)));
newValues.AddRange(existingValue.Except(newValues));