473,790 Members | 2,629 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

c# search and return values

Hello

I am trying to implement a search function within a collection of
Employees. I am searching for a specific EmpID number in the collection,
and if it is found, I want to return the Employee. This I can do.

The problem comes if the EmpID is not found in the collection. The only way
to achieve this I can think of is to throw an invalid argument exception:
public Employee WithID(int EmpID)

{

try

{

foreach(Employe e employee in personnel)

{

if (employee.EmpID == employee.EmpID)

return employee;

}

throw new ArgumentExcepti on();

}

catch (ArgumentExcept ion ae)

{

Console.Out.Wri teLine("Invalid argument passed. EmpID not in
records.{0}",ae .ToString());

Console.Out.Wri teLine(ae);

}

finally

{

return new Manager();

}
}

This of course doesn't work either, as control apparently cannot leave a
finally clause.

Any suggestions?

Thanks


Nov 15 '05 #1
3 5877
Hmm, how about linking Employee objects with their IDs in a Hashtable?
So before getting an employee, you can just check whether the key is
already there, and you can throw an exception.

I don't get what you're saying when you say control cannot leave
finally. What do you mean?

Cheers
Elder

Eric the half a Bee wrote:
Hello

I am trying to implement a search function within a collection of
Employees. I am searching for a specific EmpID number in the collection,
and if it is found, I want to return the Employee. This I can do.

The problem comes if the EmpID is not found in the collection. The only way
to achieve this I can think of is to throw an invalid argument exception:
public Employee WithID(int EmpID)

{

try

{

foreach(Employe e employee in personnel)

{

if (employee.EmpID == employee.EmpID)

return employee;

}

throw new ArgumentExcepti on();

}

catch (ArgumentExcept ion ae)

{

Console.Out.Wri teLine("Invalid argument passed. EmpID not in
records.{0}",ae .ToString());

Console.Out.Wri teLine(ae);

}

finally

{

return new Manager();

}
}

This of course doesn't work either, as control apparently cannot leave a
finally clause.

Any suggestions?

Thanks


Nov 15 '05 #2
Why not returning null to signal non-existance.
It doesn't sound right (to me) in this situation to throw an exception.
Also, you should not handle the exception within your search routine,
but let the exception pass to the caller of the search routine.
Like this the exception does not make much sense.

I would do something like this:

public Employee WithID(int EmpID)
{
foreach (Employee employee in personnel)
{
if (employee.EmpID == EmpID)
return employee.
}

// use one of these three !
return null; // to signal non-existance through the return value.
throw new ArgumentExcepti on(.....); // to signal non-existance by
throwing an exception.
return new Manager(EmpID); // return a new employee for EmpID.
}

The last option (returning a new employee) is not a good solution. You
don't know if your search
function returned an existing employee or a new employee. While (probably)
you still have to insert
it in personnel.
I should just return null.

Greetings,
Bram.
"Eric the half a Bee" <er**@half-bee.org> wrote in message
news:bu******** **@news7.svr.po l.co.uk...
Hello

I am trying to implement a search function within a collection of
Employees. I am searching for a specific EmpID number in the collection, and if it is found, I want to return the Employee. This I can do.

The problem comes if the EmpID is not found in the collection. The only way to achieve this I can think of is to throw an invalid argument exception:
public Employee WithID(int EmpID)

{

try

{

foreach(Employe e employee in personnel)

{

if (employee.EmpID == employee.EmpID)

return employee;

}

throw new ArgumentExcepti on();

}

catch (ArgumentExcept ion ae)

{

Console.Out.Wri teLine("Invalid argument passed. EmpID not in
records.{0}",ae .ToString());

Console.Out.Wri teLine(ae);

}

finally

{

return new Manager();

}
}

This of course doesn't work either, as control apparently cannot leave a
finally clause.

Any suggestions?

Thanks


Nov 15 '05 #3
Hello Eric,

Your routine is unusual, I must say.

First off, it does not make sense to raise an error at the end of a block of
code that you promptly catch. You are not catching any other errors, just
the one that you, yourself, raised.. That's not what it's for, and the code
is more complicated, difficult to follow.

Secondly, you have no reason to return from within a Finally block.

Drop the try catch block altogether.

Secondly, your design is not clear. What is the method responsible for? If
it is responsible for returning the object from a list where the object is
expect to exist, raise an error and let the calling code catch it. If it
responsible for searching a list and, if found, returning a value, then
return the value or a sentinel value (like NULL) that can be detected in the
calling code (sentinels have fallen out of favor in recent years because too
many times, errors occur when the calling code doesn't check the return).
Of the two, I prefer the idea of raising an error, but that means that you
let the calling code catch it.

Third, Console.WriteLi ne? Are you writing a console app? If so, this makes
sense. If not, consider using a logging object or a debug message handler.
The problem with Console.WriteLi ne is that these things tend to linger long
after you need them.

Fourth, what kind of Collection is it? Many collections have the ability to
find members by keys... why not use one of them, rather than having to write
your own search routine at all.

Fifth, why create a new manager? Seems like the responsibility of your
method is to return an employee object, no matter what. However, that seems
like an unlikely responsiblity. You are more likely to introduce a bug this
way.

So, my suggestions lie with the other responders:

public Employee WithID(int EmpID)
{
foreach(Employe e employee in personnel)
{
if (employee.EmpID == employee.EmpID)
return employee;
}
throw new ApplicationExce ption("Employee " + EmpID.ToString( ) + " not
found");
}

Calling code:
Employee emp;
try
{
emp = this.WithID(cur rentid);
// do something with the employee found
}
catch
{
// decide now if you want to create a new manager object.
emp = new Employee();
}

Hope this helps,
--- Nick Malik

"Eric the half a Bee" <er**@half-bee.org> wrote in message
news:bu******** **@news7.svr.po l.co.uk...
Hello

I am trying to implement a search function within a collection of
Employees. I am searching for a specific EmpID number in the collection, and if it is found, I want to return the Employee. This I can do.

The problem comes if the EmpID is not found in the collection. The only way to achieve this I can think of is to throw an invalid argument exception:
public Employee WithID(int EmpID)

{

try

{

foreach(Employe e employee in personnel)

{

if (employee.EmpID == employee.EmpID)

return employee;

}

throw new ArgumentExcepti on();

}

catch (ArgumentExcept ion ae)

{

Console.Out.Wri teLine("Invalid argument passed. EmpID not in
records.{0}",ae .ToString());

Console.Out.Wri teLine(ae);

}

finally

{

return new Manager();

}
}

This of course doesn't work either, as control apparently cannot leave a
finally clause.

Any suggestions?

Thanks


Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3667
by: todd | last post by:
here is a search tool SP I wrote. How many times have you wanted to search all your Stored procs or views (in a database) for a keyword but couldn't!? Well now you can! THis can makes life a lot easier for developers. Would you email me and let me know which part of the world my code is running in?
2
2651
by: Ryan | last post by:
I'm looking for a stored procedure (or query) to search an entire database for a specific string value and replace it with another. I'm sure I saw an SP for this a while back by someone, but cannot find it again. The SP took the search string and replace string as parameters and did the rest. Any ideas where I can find this ? Bear in mind, the idea is that this can be re-used and run on any database, so it would have to find all tables...
10
2737
by: Craig Keightley | last post by:
I have the following array: function showCPUs(){ //name brandID dualCore dualProcessor var cpuItem=; var cpuItem=; var cpuItem=; var cpuItem=; var cpuItem=; var cpuItem=; var cpuItem=;
28
3182
by: joshc | last post by:
If I have an array of data that I know to be sorted in increasing order, and the array is less than 50 elements, and I want to find the first element greater than a certain value, is a simple linear search the best here(for loop from beginning to end of array)? It seems like some other search algorithm like binary or whatever would be of no benefit on this data set.
8
2050
by: Someone | last post by:
Hi, I wish to use a dictionary.com search box and want the results of a search to open in a new window. Is there a way to do this using their code? The copy and paste code is provided below. Thanks for any help? <form method="get" action="http://dictionary.reference.com/search"> <table border="0" cellspacing="4" cellpadding="4" bgcolor="#0033ff"> <tr> <td valign="middle" align="left">
6
2711
by: zfareed | last post by:
<code> #include <iostream> #include <fstream> const int MAX_LENGTH = 10; using namespace std;
5
5276
gekko3558
by: gekko3558 | last post by:
I am writing a simple binary search tree (nodes are int nodes) with a BSTNode class and a BST class. I have followed the instructions from my C++ book, and now I am trying to get a remove method working. But before I get to the remove, I need to get my find method working. Basically, I am trying to get a "find" method working that will search for a giving int value, and return the node with that value. I have designed my current find with the...
13
2121
by: jfarthing | last post by:
Hi everyone! I am using the script below to search a db. If the is more than one match in the db, all goes well. But if there is only one match in the db, nothing gets displayed. Any suggestions will be greatly appreciated. Jim #! /usr/bin/perl -w use strict;
0
6982
by: Atos | last post by:
Binary search is used to locate a value in a sorted list of values. It selects the middle element in the array of sorted values, and compares it with the target value; that is the key we are searhing for in the array. If it islower than the target value then the search is made after that middle element and till the end of the array. If it is equal then the target value is found and the middle is returned. Otherwise, search is made from the...
6
12184
Kelicula
by: Kelicula | last post by:
Why?: One commonly used algorithm is the binary search. If you don't already know it, you should read on. Very helpful. Saves much CPU. Reduces computations exponentially. When searching though a lot of information to find a match, the first idea that comes to mind is the linear search. Loop through all the values looking for a match. If you find it, return the location, or value and end the search. However this becomes highly...
0
10413
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10200
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10145
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9021
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6769
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4094
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3707
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.