来晚了,紧急学习了一点LINQ,现在可以回答了,不知道有没有迟到
不使用LINQ的方法
不使用LINQ的修改,修改点在于将两个方法缩减至一个方法
首先,从题目可知,前后两个方法的差别在于参数列表内是否存在SceneType type
,并根据type
的有无,添加sceneConfig.SceneType == Enum.GetName(typeof(SceneType),type)
的条件判断
这意味着,要将两个方法合二为一,我们可以通过判断type
参数是否为null
实现是否需要判断sceneConfig.SceneType == Enum.GetName(typeof(SceneType),type)
但是,SceneType
是一个枚举,由于枚举是值类型,我们不能直接让枚举类型参数为null
,
我们可以使用C#的可空类型,让GetSceneByWorld()
的参数type
可以为null
至此,修改方法如下:
public static List<SceneConfig> GetSceneByWorld(SceneType? type, uint world)
{
var sceneList = new List<SceneConfig>();
foreach (var sceneConfig in SceneConfigData.Instance.List)
{
if (type == null || sceneConfig.SceneType == Enum.GetName(typeof(SceneType), type) && sceneConfig.WorldId == world)
sceneList.Add(sceneConfig);
}
return sceneList;
}
如果type == null
,我们就可以不用判断sceneConfig.SceneType == Enum.GetName(typeof(SceneType), type)
从而实现两个方法合二为一
使用LINQ
使用LINQ的修改,修改点在于将foreach
代码块直接替换为LINQ语法
如果我们愿意使用LINQ的语法的话,在上一题代码的基础上,就可以将foreach
语法块的内容,直接缩减到一句语句
首先使用链式表达式,也就是对对象连续使用LINQ相关拓展方法的代码
public static List<SceneConfig> GetSceneByWorld(SceneType? type, uint world)
{
List<SceneConfig> sceneList = SceneConfigData.Instance.List.Where(sceneConfig => sceneConfig.WorldId == world && type == null || sceneConfig.SceneType == Enum.GetName(typeof(SceneType), type)).ToList();
return sceneList;
}
其中Where
方法是将List
内元素config
取出,再通过=>
后的条件表达式来筛选满足条件的元素,这里我们就可以直接把之前if
的条件语句移植到这里
最后的ToList()
是将通过Where
方法返回的可迭代类型IEnumerable<>
转化为列表List<>
LINQ还有另外一种类似于SQL语句的查询表达式的写法
public static List<SceneConfig> GetSceneByWorld(SceneType? type, uint world)
{
var sceneList = from sceneConfig in SceneConfigData.Instance.List //将所有元素从SceneConfigData.Instance.List挑出
where type == null || sceneConfig.SceneType == Enum.GetName(typeof(SceneType), type) && sceneConfig.WorldId == world //挑选符合条件的sceneConfig
select sceneConfig; //将符合条件的sceneConfig放入sceneList
return sceneList.ToList(); //将sceneList转换为List<SceneConfig>类型再返回
}
效果和上面是一样的
LINQ是紧急学习的,再加上代码没办法直接通过IDE审查(我这里使用VSCode编辑的),因此可能有错误,望海涵(doge)