如何在C# LINQ中进行搜索

lsmepo6l  于 2022-12-25  发布在  C#
关注(0)|答案(3)|浏览(192)

我有一个字符串搜索查询,我从前端应用程序,但我有一个问题的查询。
我有一个ID为(number = int)的对象列表。
如果用户将在搜索框中写入编号12(字符串),则他应该具有ID中包含编号12的所有对象列表。
物体(1、8、80、90、180);另一个例子是,如果用户输入数字8,他应该输出8,80,180;
如何为这样的问题编写linq?
任何示例都要记住,搜索查询是字符串,ID是数字:(

2exbekwf

2exbekwf1#

using System;
using System.Linq;
                    
public class Program
{
    public class MyObject
    {
        public int Id { get; set; }
    }
    
    public static void Main()
    {
        var arr = new MyObject[]
        {
            new MyObject() { Id = 1 },
            new MyObject() { Id = 8 },
            new MyObject() { Id = 80 },
            new MyObject() { Id = 90 },
            new MyObject() { Id = 180 }
        };

        var searchQuery = "8";
        
        var result = arr.Where(x => x.Id.ToString()
            .Contains(searchQuery))
            .Select(x => x.Id)
            .ToList();
        
        Console.WriteLine(String.Join(",", result));
    }
}

https://dotnetfiddle.net/AiIdg2

8cdiaqws

8cdiaqws2#

听起来你想要这样的东西

var input = "8";
var integers = new[] { 8, 80, 810, 70 };
var result = integers.Where(x => x.ToString().Contains(input));
ohtdti5x

ohtdti5x3#

像这样的事情就足够了:

using System.Globalization;

namespace ConsoleApp2
{
  internal class Program
  {
    static void Main(string[] args)
    {
      var items = new[]
      {
        new Item { Id = 8 },
        new Item { Id = 18 },
        new Item { Id = 80 },
        new Item { Id = 6 },
        new Item { Id = 13 },
      };

      var itemsWithSearchString = items
        .Select(x => new { Item = x, SearchString = x.Id.ToString(CultureInfo.InvariantCulture) })
        .ToArray();

      const string userInput = "8";

      var matchingItems = itemsWithSearchString
        .Where(x => x.SearchString.Contains(userInput, StringComparison.Ordinal))
        .Select(x => x.Item)
        .ToArray();

      foreach (var item in matchingItems)
      {
        Console.WriteLine($"Matching item: {item}");
      }
    }
  }

  public class Item
  {
    public int Id { get; set; }

    public override string ToString()
    {
      return $"Id {this.Id}";
    }
  }
}

相关问题