'Unable to declare and access a List for a live search functionality
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 class="text-muted ml-5">
Showing @FilteredToDos.Count out of @ToDoItems.Count
</span>
<h4 class="mt-4">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?)
Solution 1:[1]
Few issues in your attached code besides the i.0,
Issues:
itemsclass is missing.- You can't assign a
List<string>value to the variable ofList</* class */>type.
Solution:
- Declare a
ToDoItemclass.
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong Shun |

