3 methods in C# to get List.FindAll

Published on Friday, October 29, 2010

How do you have the code to Find something from a List?

Here I provided 3 ways to implement it and I have tested to confirm all of them worked:

Assume I have a list which get some data items from somewhere:

List<CPoint> tempPointList = GetCPointsBy(pointType, trunkAddr, sensorAddr, pName);

Now I want to search something by some conditions from the ‘tempPointList’, and also I need to consider the user's selection from screen (see below) :

When the user checks on the ‘Alarm’ option, I need to find all 'Alarm' types, when user checks on the ‘ComFail and SensorFail’, I need to find all 'ComFail and SensorFail' types, if both of them are checked on, I need to find all items that match both of them;

Method 1:


List<CPoint> listPoint = null;

try
{
    List<CPoint> tempPointList = GetCPointsBy(pointType, trunkAddr, sensorAddr, pName);

    if (tempPointList != null)
    {
        var Number = from pnt in tempPointList
                     where
                     (isComFailReq ? ((pnt.PointRealTimeData.Status & Common.CSTAT_COMFAIL) != 0) : (1 != 1))
                     || (isAlarmReq ? ((pnt.PointRealTimeData.Status & Common.CSTAT_ALARM) != 0) : (2 != 2))
                     select pnt;

        if (Number.Count() > 0)
        {
            listPoint = new List<CPoint>();

            foreach (var m in Number)
            {
                listPoint.Add((CPoint)m);
            }
        }
    }
}
catch (Exception e)
{
    throw e;
}

return listPoint;

Method 2:

List<CPoint> listPoint = null;

try
{
    List<CPoint> tempPointList = GetCPointsBy(pointType, trunkAddr, sensorAddr, pName);

    if (tempPointList != null)
    {
        listPoint = (List<CPoint>)(tempPointList.FindAll(item => ((isComFailReq ? ((item.PointRealTimeData.Status & Common.CSTAT_COMFAIL) != 0) : (1 != 1))
                   || (isAlarmReq ? ((item.PointRealTimeData.Status & Common.CSTAT_ALARM) != 0) : (2 != 2)))));
    }
}
catch (Exception e)
{
    throw e;
}

return listPoint;

Method 3:

List<CPoint> listPoint = null;

try
{
    List<CPoint> tempPointList = GetCPointsBy(pointType, trunkAddr, sensorAddr, pName);

    if (tempPointList != null)
    { 
      listPoint = (List<CPoint>)(tempPointList.FindAll(delegate(CPoint cp)
                 {
                     //return ((0 & Common.CSTAT_COMFAIL) != 0);
                     return ((isComFailReq ? ((cp.PointRealTimeData.Status & Common.CSTAT_COMFAIL) != 0) : (1 != 1))
                         || (isAlarmReq ? ((cp.PointRealTimeData.Status & Common.CSTAT_ALARM) != 0) : (2 != 2)));
                 }));
    }
}
catch (Exception e)
{
    throw e;
}

return listPoint;

Actually, We might have the method 4, but it is almost the same as method 3, which is just separate the delegate class to a separate class, and load this method in "tempPointList.FindAll(separate delegate class name)".