These days I read C # code from various people and I found it funny how people keep using what they learned years ago even though things have changed. I put the following example:
a collection is available (_modules) and Module objects need a method to return only module names containing the string that is passed. Public
GetModulesCalled Module (string name) {
for (int i = 0; i \u0026lt;_modules.Count; i + +)
if (_modules [i]. Name == name) return
modules [i];
return null;}
to return null if no match is very much like me. What I do not think it is important that you look if more than one module has the same name. It may be best to throw an exception, but of course, the code would become a bit more cumbersome:
GetModulesCalled public Module (string name)
{bool found = false;
Module bull = null;
for (int i = 0; i \u0026lt;_modules.Count; i + +)
if (_modules [i]. Name == name)
if (found ) throw new ArgumentException
("Two or more modules Have the name:" + name);
else {
bull = modules [i];
found = true;}
bull
return;}
Another implementation
I found a "want but do not know how" public
GerModuleCalled Module (string name)
{var query = (from x in _modules WHERE name == x.Name select x);
if (query.Count == 1) return
query.First ();
return null;}
Here
null will be returned if there both as if more than one. Not that I really liked the idea, but could be accepted. In any case, I propose this alternative, I believe, is rather simple: public
GetModuleCalled Module (string name) {
_modules.SingleOrDefault return (x => x.Name == name);
0 comments:
Post a Comment