查找字符串是否在其他字符串中

时间:2018-05-09 12:44:47

标签: c# linq

我有一个包含单词的字符串。

string attrs = "AAA,BBB,CCC,DDD"

我有想要检查其中一个对象是否存在于此字符串中的对象列表,如果没有,则过滤掉该对象

List<Vehicle> vehiclesSort = new List<Vehicle>();

所以我试着做这样的事情:

vehiclesSort = vehiclesSort.Where(o => o.Class.Contains(attrs))

但是编译错误,

此外我需要检查attrs中是否存在Class属性,而不是如果属性中存在attrs,那么我认为我的方向不正确

请协助,

2 个答案:

答案 0 :(得分:2)

我稍微修改了你的查询。这是一个例子:

List<Vehicle> vehiclesSort = new List<Vehicle>()
{
    new Vehicle() {Class="VW" },
    new Vehicle() {Class="BBB" },
    new Vehicle() {Class="BMW" },
    new Vehicle() {Class="DDD" },
    new Vehicle() {Class="AUDI" },
};

string attrs = "AAA,BBB,CCC,DDD";

vehiclesSort = vehiclesSort.Where(x => attrs.Split(',').Contains(x.Class)).ToList();

Vehicle上课:

public class Vehicle
{
    public string Class { get; set; }
}

<强> Session.refresh()

答案 1 :(得分:0)

我认为你正在寻找像这样的东西

class Program
    {
        static void Main(string[] args)
        {
            string attrs = "AAA,BBB,CCC,DDD";
            List<Vehicle> vehiclesSort = new List<Vehicle>();
            vehiclesSort.Add(new Vehicle(attrs));
            vehiclesSort.Add(new Vehicle("bbb"));
            vehiclesSort = vehiclesSort.Where(o => o.attr.Contains(attrs)).ToList();

            foreach (var VARIABLE in vehiclesSort)
            {
                Console.WriteLine(VARIABLE.attr);
            }
        }
    }

    public class Vehicle
    {
        public Vehicle(string attr1)
        {
            this.attr = attr1;
        }

        public string attr;
    }