public class Country
{
public string Name { get; set; }
public List<City> Cities { get; set; }
}
public class City
{
public string Name { get; set; }
}
public static void Main()
{
var items = new List<Country>()
{
new Country() { Name = "Austria", Cities = new List<City>() { new City() { Name = "Vienna" }, new City() { Name = "Linz" } } },
new Country() { Name = "Australia", Cities = new List<City>() { new City() { Name = "Sydney" }, new City() { Name = "Melbourne" } } },
new Country() { Name = "USA", Cities = new List<City>() { new City() { Name = "Austin" }, new City() { Name = "New York" } } }
};
var searchTerm = "aus";
var filteredItems = items.Where(i => i.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
i.Cities.Any(c => c.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)))
.Select(i => new Country()
{
Name = i.Name,
Cities = i.Cities.Where(c => c.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
i.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList()
})
.ToList();
Console.WriteLine("****Unfiltered:");
Output(items);
Console.WriteLine("\r\n****Filtered:");
Output(filteredItems);
}
public static void Output(List<Country> countries)
{
foreach (var country in countries)
{
Console.WriteLine(country.Name);
foreach (var city in country.Cities)
{
Console.WriteLine(" " + city.Name);
}
}
}
输出量:
****Unfiltered:
Austria
Vienna
Linz
Australia
Sydney
Melbourne
USA
Austin
New York
****Filtered:
Austria
Vienna
Linz
Australia
Sydney
Melbourne
USA
Austin
1条答案
按热度按时间iezvtpos1#
看一下这个Fiddle,并对其进行修改以使用一个名为
TextChanged
的TextBox
事件。提琴码:
输出量: