8

我有一个清单。

可能的成员 (x123, y123, z123, a123, b123, c123).//123 是示例 此“mylist”可能包含以 x 开头的成员,也可能不包含。这对于 y,z,a,b,c 也是一样的。

If contains a member starts with x:
//Formula Contains X

If Not Contains a member starts with x:
//Formula Not Contains X

//same as all of x,y,z,a,b,c. But unlike a foreach, I must place the formulas at checking time, not after.

我怎样才能做到这一点?

4

4 回答 4

16

检查列表中是否有任何以“x”开头的项目:

bool result = mylist.Any(o => o.StartsWith("x"))

检查列表中是否没有以“x”开头的项目:

bool result = !mylist.Any(o => o.StartsWith("x"));
于 2013-06-04T18:28:14.387 回答
6

你可以使用.AnyLinq

bool result = mylist.Any(o => o.StartsWith("x"));

这将在列表上进行迭代并告诉您是否至少有一个以“x”开头的元素

于 2013-06-04T18:23:33.413 回答
2
List<string> formula = new List<string> { "x123", "y123" };
string variable = "x";
bool containsVariable = formula.Any(s => s.StartsWith(variable));
于 2013-06-04T18:23:06.393 回答
2
public void Process(List<string> list, string key)
{
    if (list.Any(i => i.StartsWith(key)))
    {
        //Formula Contains key
    }
    else
    {
        //Formula Not Contains key
    }
}

然后你可以打电话

List<string> list = new List<string> { "x123", "y123", "z123", "a123", "b123", "c123"};
Process(list, "x");
Process(list, "a");
于 2013-06-04T18:23:31.680 回答