比较String with split in contains - LINQ

时间:2011-07-01 10:35:57

标签: linq

我的要求是将字符串中的值与字符串列表进行比较。

代码:

string Names = "Prabha,Karan";
        List<string> Presenter = new List<string> { "Prabha", "Joe", "Hukm" };

bool Presented = Presenter.Contains(Names.Split(','));

上面的代码抛出一个错误,在这里我需要找到名称出现在演示者中(Presenter有名称的分割值)。

2 个答案:

答案 0 :(得分:5)

你可以这样做:

var splitNames = Names.Split(',');
bool Presented = Presenter.Any(p => splitNames.Contains(p));

编辑:

如果您对匹配的内容感兴趣,请执行以下操作:

var matches = Presenter.Where(p => splitNames.Contains(p))

答案 1 :(得分:0)

string names = "Prabha,Karan"; 
List<string> presenter = new List<string> { "Prabha", "Joe", "Hukm" };
IEnumerable<string> namesList = names.Split(',').Select(x => x.Trim());
var list = presenter.Intersect(namesList);
bool presented = namesList.Count() == list.Count());

该单元测试覆盖您的情况:

[Test]
public void AllSourceEntriesAreFoundInTheTargetList()
{
    string names = "Prabha,Karan"; 
    List<string> presenter = new List<string> { "Prabha", "Joe", "Hukm" };
    IEnumerable<string> namesList = names.Split(',').Select(x => x.Trim());

    var list = presenter.Intersect(namesList);
    Assert.AreNotEqual(namesList.Count(), list.Count());

    presenter = new List<string> { "Prabha", "Karan", "SomeAnother" };
    var list1 = presenter.Intersect(namesList);
    Assert.AreEqual(namesList.Count(), list1.Count());
}