Home > Blockchain >  Unable to declare and access a List for a live search functionality
Unable to declare and access a List for a live search functionality

Time:04-13

as the title says I am new to C# and I am currently having trouble making this script work.

It is supposed to define a List with some dummy text and for searching purposes.

Here is the code:

@page "/livesearch"
@using System.Collections.Generic

<input @bind-value="SearchTerm" @bind-value:event="oninput" />

<span >
    Showing @FilteredToDos.Count out of @ToDoItems.Count
</span>

<h4 >To Do's</h4>
<ul>
    @foreach (var toDo in FilteredToDos)
    {
        <li>@toDo.Name</li>
    }
</ul>

@code {
    // Initialize SearchTerm to "" to prevent null's
    string SearchTerm { get; set; } = "";

    // Imagine this was retrieved from an API, just hardcoding for demo purposes
        List<string> items = new List<string>() { "foo", "bar", "foobar" };

    List<items> FilteredToDos => items.Where(i => i.0.ToLower().Contains(SearchTerm.ToLower())).ToList();
}

The problem is coming from the last line, namely from items in List<items> FilteredToDos and the i.0.ToLower() part.

The error says

The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)

Update with screenshot: enter image description here

CodePudding user response:

Few issues in your attached code besides the i.0,

Issues:

  1. items class is missing.
  2. You can't assign a List<string> value to the variable of List</* class */> type.

Solution:

  1. Declare a ToDoItem class.
public class ToDoItem
{
    public string Name { get; set; }
}

2.1. items should be List<ToDoItem> type.

2.2. Filter by item.Name that contains SearchTerm (suggested by @MindSwipe to work with string.Contains() ignore case sensitive).

List<ToDoItem> items = new List<ToDoItem>() 
{ 
    new ToDoItem { Name = "foo" }, 
    new ToDoItem { Name = "bar" }, 
    new ToDoItem { Name = "foobar" }
};

List<ToDoItem> FilteredToDos => items
    .Where(i => i.Name.Contains(SearchTerm, StringComparison.InvariantCultureIgnoreCase))
    .ToList();
  • Related