我需要一些帮助,我的方法在我的课程中重复了6次,每个方法中唯一改变的是LINQ属性(在示例中为"名字",但我也有一个用于姓氏,公司名称,用户ID,状态).我想帮助重构一下,这样我就可以只使用一种方法,使属性成为动态或传入.
private static IQueryable<MyModel> FilterFirstName(IQueryable<MyModel> query, string searchText, string searchFilter)
{
switch (searchFilter.ToLower())
{
case "contains":
query = query.Where(x => x.FirstName.ToLower().Contains(searchText.ToLower()));
break;
case "does not contain":
query = query.Where(x => !x.FirstName.ToLower().Contains(searchText.ToLower()));
break;
case "starts with":
query = query.Where(x => x.FirstName.StartsWith(searchText, StringComparison.InvariantCultureIgnoreCase));
break;
case "ends with":
query = query.Where(x => x.FirstName.EndsWith(searchText, StringComparison.InvariantCultureIgnoreCase));
break;
case "equals":
query = query.Where(x => x.FirstName.Equals(searchText, StringComparison.InvariantCultureIgnoreCase));
break;
}
return query;
}
Run Code Online (Sandbox Code Playgroud) 在最近的一次采访中,我被要求编写一个程序,其中列出了实现鸣喇叭界面的不同车辆或其他任何车辆,使用抽象类,然后对不同的车辆使用不同的鸣喇叭.这是我到目前为止所提出的,只要我单独调用这些方法,它就能正常工作.但是当我尝试将它们放入IEnumerable中,然后迭代时,它会显示抽象类的honk,而不是单个类.谁能解释我做错了什么?
using System;
using System.Collections.Generic;
namespace ConsoleHonk
{
class Program
{
static void Main(string[] args)
{
var myList = GetVehicles();
//This doesn't display the correct honk
myList.ForEach(x => x.honk());
}
private static List<IHonker> GetVehicles()
{
var myList = new List<IHonker>();
var myTruck = new Truck();
var myCar = new Car();
var myGoose = new Goose();
myList.Add(myTruck);
myList.Add(myGoose);
myList.Add(myCar);
return myList;
}
}
class Goose : HonkClass
{
public virtual void honk()
{
Console.WriteLine("Quack");
}
}
class Car : HonkClass
{ …Run Code Online (Sandbox Code Playgroud)