【问题标题】:Search in the List Item Using C#使用 C# 在列表项中搜索
【发布时间】:2019-03-29 10:49:15
【问题描述】:

我有这样的逗号分隔 ID 值:3,4,5,7,这对于表中的每条记录都不同。

现在从配置设置中有特定的值,例如:3,4

我需要有只选择与配置值匹配的记录的代码:3,4

【问题讨论】:

  • 请添加示例代码和数据进行查询。然后告诉我们应该选择哪些记录。
  • @user1941025:我们需要示例代码,请:-)
  • 代码示例的一个具体问题:您的问题被标记为 linq to objects;但是您在表格中提到了记录。对于 linq-to-objects 和 linq-to-sql,答案(我希望你会需要)会有所不同;所以最好确保我们回答正确。

标签: c# list linq linq-to-objects


【解决方案1】:

您可以使用string.split 将逗号分隔值的字符串转换为单个值的列表。

然后,您可以使用 linq 从一个列表中查找也在另一个列表中的所有值。

var results = tableValues.Where(t => configValues.Contains(t));

【讨论】:

    【解决方案2】:

    Foreach 元素,您将其拆分,然后搜索您的键。 试试这个:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Program
    {
        private static List<string> lstStr = new List<string>
        {
            "1,2,3,4", 
            "3,4,5", 
            "3,4,5,6,7,8,9"
        };
    
        private static string[] search = new[]{"3", "4"}; // "3,4".Split(',')
    
        public static void Main()
        {
            foreach(var el in lstStr.Where(x => SearchFunction(x, search)))
            {
                Console.WriteLine(el);
            }
        }
    
        private static bool SearchFunction(string listItem, string[] search)
        {
            var hashSet = listItem.Split(',').ToHashSet();
            return search.All(hashSet.Contains);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 2013-03-06
      相关资源
      最近更新 更多