运行测试时,不会显示包含来自其他2个数组的相交字符串的数组



我想知道是否有人可以帮助!

当测试运行时,我的foreach循环没有被击中。

我想我忽略了一些东西,但却看不到它。

这是类

using System.Linq;
using System;
using System.Collections.Generic;
public class Challenge
{
public static string[] FindIntersection(string[] first,string[] second)
{
var intersect = first.Intersect(second);

string[] intersectArr = new string[1];

foreach (string res in intersect) {
intersectArr.Concat(new string[] {res}).ToArray();
return intersectArr;
}

return null;

这里是测试类

using System.Collections.Generic;
using NUnit.Framework;
using System;
[TestFixture]
public class FindIntersectionTest
{
[Test]
public void ShouldReturnAnEmptyArrayWhenNoElementsAreCommon()
{
Assert.AreEqual(new string[] {}, Challenge.FindIntersection(new string[] {"a","b"},new string[] {"c","d"}));
}
[Test]
public void ShouldReturnTheCommonElementWhenThereIsOneElementInCommon()
{
Assert.AreEqual(new string[] {"a"}, Challenge.FindIntersection(new string[] {"a","b"},new string[] {"a","B"}));
}
[Test]
public void ShouldReturnTheFirstThreeCommonElementsWhenThereAreMoreThanThreeElementsInCommon()
{
Assert.AreEqual(new string[] {"b","c","d"}, Challenge.FindIntersection(new string[] {"a","b","c","d","e","f"},new string[] {"e","d","c","b"}));
}
}

控制台输出为

FindIntersectionTest
ShouldReturnAnEmptyArrayWhenNoElementsAreCommon
Test Failed
Expected: <empty>
But was:  null
Completed in 79.3480ms
ShouldReturnTheCommonElementWhenThereIsOneElementInCommon
Test Failed
Expected and actual are both <System.String[1]>
Values differ at index [0]
Expected: "a"
But was:  null
Completed in 6.9410ms
ShouldReturnTheFirstThreeCommonElementsWhenThereAreMoreThanThreeElementsInCommon
Test Failed
Expected is <System.String[3]>, actual is <System.String[1]>
Values differ at index [0]
Expected: "b"
But was:  null

我不知道该怎么解决这个

intersectArr.Concat(new string[] {res}).ToArray();在这里是Toarray创建一个副本并返回。而是像这样做

intersecArr = intersectArr.Concat(new string[] {res}).ToArray();

但是@ programman在评论中说的更好

最新更新