从自定义列表中删除项目

时间:2016-08-08 09:57:41

标签: c# list

我有List<Fill> items

以下是Fill类:

public class Fill
{
    public string arret { get; set;}
    public string ligneSens { get; set;}
}

如何使用字符串值arretligneSens从此列表中删除项目?

示例:

void OnDelete(object sender, EventArgs e, string arretName, string ligneSensName)
{
    var aFill = new Fill
    {
        arret = arretName,
        ligneSens = ligneSensName
    };

    items.Remove(aFill); //<--- this doesn't work
}

很抱歉这篇文章的标题我不知道怎么问。

3 个答案:

答案 0 :(得分:6)

您应该覆盖Equals的{​​{1}}和GetHashCode方法。当您在引用类型(类)上调用object时,它将通过它的Remove方法查找一个。

Equals

有关public class Fill { public string arret { get; set; } public string ligneSens { get; set; } public override bool Equals(object obj) { var other = obj as Fill; if(other == null) return false; return other.arret == arret && other.ligneSens == ligneSens; } public override int GetHashCode() { return arret.GetHashCode() ^ ligneSens.GetHashcode(); } } 覆盖在线搜索的最佳做法,有很多问题

另一种方法是,通过传递谓词来评估集合中的每个项目来具体说明remove的内容:

GetHashCode()

答案 1 :(得分:4)

你必须使用RemoveAll(),目前你正在传递一个新创建的对象,其中items没有信息,因为它是一个新的引用而不是相同的引用:

void OnDelete(object sender, EventArgs e, string arretName, string ligneSensName)
{
   items.RemoveAll(item => item.arret == arretName &&  item.ligneSens == ligneSensName);
}

答案 2 :(得分:2)

使用列表API RemoveAll

;WITH Punch_logs_U as (SELECT distinct userid, logdate,direction from punch_logs), IN_OUT_TIMES AS (SELECT P1.USERID, P1.LOGDATE, P1.DIRECTION, P2.Logdate Logdate_out, P2.Direction Direction_out FROM Punch_Logs_u P1 OUTER APPLY (SELECT TOP 1 PC.Logdate, PC.Direction From Punch_Logs_u PC WHERE PC.UserId = P1.UserId AND PC.Direction = 'OUT' AND PC.Logdate >= P1.Logdate) P2 WHERE P1.Direction = 'IN' AND NOT EXISTS (SELECT 0 FROM Punch_Logs_u P3 WHERE P3.UserID = P1.UserId AND P3.direction = 'IN' AND P3.logdate > P1.Logdate AND P3.Logdate <= P2.Logdate) ) SELECT IO.USERID, IO.Logdate LogDate_in, io.Logdate_out, DATEDIFF(minute,io.logdate, io.logdate_out) TimeInMins , DATEDIFF(minute,LAG(logdate, 1,io.logdate) over (partition by userid order by logdate), io.logdate) TimeOUTMins FROM IN_OUT_TIMES IO order by userid, io.logdate