Home > Net >  How to search in C# LINQ
How to search in C# LINQ

Time:12-21

I have a string search query which I have from the frontend app but I have a problem with the query.

I have a list of objects which have Id (number = int).

If the user will write in the search box number 12(string) he should have all lists of objects which contains the number 12 in id.

Objects (1,8,80,90,180); Another example is if the user will input the number 8. He should have output 8,80,180;

How to write linq for questions about such a thing?

Any example remember search query is a string and id is a number :(

CodePudding user response:

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

CodePudding user response:

Sounds like you want something like this

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

CodePudding user response:

Something like this could be enough:

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}";
    }
  }
}
  • Related