1

我在下面有这段代码——一个将 List 作为输入参数之一的通用方法。在该方法中,是一个 IF/ELSEIF 语句,它运行到一个常见的 LINQ 调用中。请帮帮我,以便所有 IF/ELSEIF 都可以使用 LINQ 调用。

private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
{
    if (anyOutdoorSports == null){ return false ;}
    Boolean _returnValue = false;

    if (anyOutdoorSports.GetType() == typeof(List<Swimming>))
    {
        List<Swimming> Swimming = anyOutdoorSports.Cast<Swimming>().ToList();

        if (Swimming.Count > 0)
        {
            int listCount = (from rca in Swimming
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }
    else if (anyOutdoorSports.GetType() == typeof(List<Tennis>))
    {
        List<Tennis> Tennis = anyOutdoorSports.Cast<Tennis>().ToList();

        if (Tennis.Count > 0)
        {
            int listCount = (from rca in Tennis
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }
    else if (anyOutdoorSports.GetType() == typeof(List<Soccer>))
    {
        List<Soccer> Soccer = anyOutdoorSports.Cast<Soccer>().ToList();

        if (Soccer.Count > 0)
        {
            int listCount = (from rca in Soccer
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }

    return _returnValue;
}

感谢所有查看和帮助的人。

4

3 回答 3

2

如果 , 有一个公共基类TennisSoccer并且Swimming有一个RecordFields属性,这很简单:

private boolean FilterList<T>(IEnumerable<T> anyOutdoorSports, int numberOfParticipants) where T : OutdoorSport
{
    if(anyOutdoorSports == null) return false;
    return anyOutdoorSports.Any(s => s.RecordFields[numberOfParticipants].ToString().StartsWith("stamina"));
}
于 2012-06-18T18:13:49.990 回答
0

由于您的所有类型似乎都有一个 RecordFields 属性,您可以添加一个接口并使用它而不是通用。

除此之外,您必须求助于 Func<> 表达式。

于 2012-06-18T18:11:27.817 回答
0

假设所有类都继承自同一个基类,其中包含RecordFields,您可以在方法上创建通用约束并ifs完全删除。

private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
  where T : OutdoorSport
{
    if (anyOutdoorSports == null){ return false ;}
    Boolean _returnValue = false;

    if (anyOutdoorSports.Count > 0)
    {
        int listCount = (from rca in anyOutdoorSports
                         where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                         select rca).Count();
        _returnValue = listCount > 0;
    }

    return _returnValue;
}
于 2012-06-18T18:13:35.587 回答