StartsWith和Contains在列表中的用法<;字符串>;

本文关键字:lt 字符串 gt 用法 Contains 列表 StartsWith | 更新日期: 2023-09-27 18:16:49

我有一个列表。

它可能是成员(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.

我该怎么做?

StartsWith和Contains在列表中的用法<;字符串>;

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

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

检查是否没有项目以"x"开头您的列表:

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

您可以从Linq 使用.Any

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

这将在列表上迭代,并告诉您是否至少有一个元素以"x">

开头
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");
List<string> formula = new List<string> { "x123", "y123" };
string variable = "x";
bool containsVariable = formula.Any(s => s.StartsWith(variable));