我有以下代码可行,但希望更可重用或得到相同的结果。我想要一个通用的Remove_At_Weight
函数,而不是Remove_At_Code
和Remove
函数,您可以选择要比较的字段以及与之比较的字段。
例如,我可能有另一个名为Recordo_3
的对象,它有第三个字段
"字符串描述"
我想检查这个字段而不必写一个新的" Remove_At_Description"功能
我可能从错误的角度接近这个问题,并且有更好的方法可以使用设计图案等来实现。如果是这样,请提供建议。希望这是有道理的。
class Recordo
{
private string _code;
public string Code
{
get { return _code; }
set { _code = value; }
}
private int _weight;
public int Weight
{
get { return _weight; }
set { _weight = value; }
}
}
private void Form1_Load(object sender, EventArgs e)
{
List<Recordo> lr = new List<Recordo>();
lr.Add(new Recordo() {Code = "QQQ", Weight = 10});
lr.Add(new Recordo() { Code = "AAA", Weight = 20 });
lr.Add(new Recordo() { Code = "AAA", Weight = 10 });
lr.Add(new Recordo() { Code = "QQQ", Weight = 10 });
lr = Remove_At_Code(lr,"QQQ");
lr = Remove_At_Weight(r, "20");
MessageBox.Show("Done!");
}
private static List<Recordo> Remove_At_Weight(List<Recordo> lr, int weight)
{
for (int i = lr.Count-1; i > -1; i--)
{
if (lr[i].Weight == weight)
{
lr.RemoveAt(i);
}
}
return lr;
}
private static List<Recordo> Remove_At_Code(List<Recordo> lr, string code)
{
for (int i = lr.Count-1; i > -1; i--)
{
if (lr[i].Code == code)
{
lr.RemoveAt(i);
}
}
return lr;
}
答案 0 :(得分:1)
像@Matthias一样Herrmann说你可以使用ICompareable接口,但说实话这个任务非常简单,你可以用一个简单的linq查询来实现它。例如:
var theList = new List<Recordo>(); // lets assume it already have some records
var someCode = "QQQ";
var someWeight = 15;
theList.RemoveRange(theList.Where(x => x.Code == someCode));
//OR the following for weight
theList.RemoveRange(theList.Where(x => x.Weight == someWeight ));
答案 1 :(得分:1)
首先让我们在没有你要求的通用方法的情况下这样做(为此你可以考虑使用属性名称反映 - 见下文)。您可以使用Linq
这样的
lr.RemoveAll(r => r.Code.Equals("QQQ"));
lr.RemoveAll(r => r.Weight == 20);
现在如果您真的想要这种通用方法,可以试试这个
public static class MyExtension
{
public static void RemoveAllWithPropertyValue<T>(this List<T> list, string propertyName, object value)
{
var property = typeof(T).GetProperty(propertyName);
list.RemoveAll(item => property.GetValue(item, null).Equals(value));
}
}
并将此自定义扩展程序用作
lr.RemoveAllWithPropertyValue("Code", "QQQ");
lr.RemoveAllWithPropertyValue("Weight", 20);
注意:这不是类型安全的,我们没有进行任何验证!
答案 2 :(得分:1)
您可以{/ 3}}使用
lr.RemoveAll(item => item.Code == "QQQ");
lr.RemoveAll(item => item.Weight == 20);
您不需要自己的通用功能,因为上面提到的方法就是为您做的。
答案 3 :(得分:0)
使用LINQ会简单得多:
这将获得权重不是7的所有项目。
lr = lr.Where( item => item.Weight != 7 ).ToList();
或者,如果您想让它更像原始代码:
你可以传递一个函数
并称之为:
lr = GenericRemove( lr, item => item.Weight == 7 );
private static List<Recordo> GenericRemove(List<Recordo> lr, Func<Recordo, bool> filter)
{
for (int i = lr.Count-1; i > -1; i--)
{
if ( filter( lr[i]) )
{
lr.RemoveAt(i);
}
}
return lr;
}