How to retrieve a specific object from a list in C# based on the value of a field

wademi
wademi used Ask the Experts™
on
   
      I have an object call video(See video class below ) in my C# application.
      
      I have a list like    List<object> mylist = new List<object>();
      
      I have a while loop where objects are added to the list
      
      While{
      Video myvideo = new Video(id,path);
            mylist.add(myvideo)
            

      }
      
      I would like to include in the while loop code that checks if an object exsist based on ONLY the ID since the path may be different.
      If the ID exsist I would like to retrieve the path for that object.
      
      Can you show me code examples of the following:
      
      1. Check if object exsist with a particular ID.
      2. Get the Path value for that object based on the ID.
      3. Remove the object for that ID.
      
      
      
      
      class Video
    {

        private string id;
        private string Path;

        public Video(string id, string Path)
        {
            this.MyPath = Path;
            this.Myid = id;
        }


        public string Myid
        {
            get{return id;}
            set{ id = value;}
        }
        public string MyPath
        {
            get { return Path; }
            set { Path = value; }
        }


    }
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Hi, first of all, why do you have a list of object instead of a list<Video> ?

Commented:
The whole idea of a Generic List is that you don't box and unbox your class in an Object (Performances degradation due to boxing and unboxing, and also not knowing which object you are working with).


You can use Linq...

var myVideos = (from val in mylist
                          where val is (Video && val as Video).ID == "123"
                          select val).ToList();

Now you can check the number of found results:

if (myVideos.Count > 0)
{
  // We have found 1 or more videos with the ID that we searched for...
   /// Do your code here
}
else
{
   // Do your Else code here
}

Commented:
Btw, shouldn't ID by an int rather than a string?


And if you make your list to be:
List<Video> mylist = new List<Video>();

then you can write the Linq as (because you know the items in the list are videos):
var myVideos = (from val in mylist
                          where  val.ID == "123"
                          select val).ToList();
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Commented:
Oops, in the Linq, ask for Myid ==
and not for ID ==

Author

Commented:
saragani: Thanks for your help

The program I am building is a small console app. I would like to build the way I have started and have my specific questions answered. I am not an expert prgrammer so I dont want to confuse myself with this linq stuff.

Commented:
All right then...

string path = "";
foreach (object obj in mylist )
{
    if (obj is Video)
    {
        Video video = obj as Video;
        if (video.Myid == "12345") // Replace 12345 with the ID you are looking for...
        {
            path = video.MyPath; // Do whatever you want with this path.
            mylist .Remove(video); // you wanted to remove the object after it is found, so here it is.
            break; // stop searching... we have found our object
        }
    }
}
I have a Perfect Solution created just for you .. here it is plz check and run this code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace CollectionClasses
{
	public class CollectionClass
	{
		List<object> mylist;
		public CollectionClass()
		{
			//Default Constructor
			mylist = new List<object>();
		}		
		
		public static void AddVideo(int id,string path)
		{
			Video video = new Video(id,path);
			mylist.Add(video);
			
		}

		public static bool CheckVideoExists(int id)
		{
			bool result = false;
			Video video = null;
			foreach(object o in mylist)
			{
				video = (Video)o;
				if(video.Myid == id)
				{
					result = true;	
				}
			}
			return result;
		}		
		
		public static string GetVideoPath(int id)
		{
			string path = "";
			Video video = null;
			foreach(object o in mylist)
			{
				video = (Video)o;
				if(video.Myid == id)
				{
					path = video.MyPath;	
				}
			}
			return path;
		}

		public static void AddVideos(int NoOfVideos)
		{			
			int j = 0;
			while(j<NoOfVideos)
			{
				int id = j+1;
				AddVideo(j,@"C:\MyVideos\video"+id.ToString()+".avi");
                                j++; 		
			}			
		}		

		public static bool RemoveVideo(int id)
		{
			bool result = false;
			try
			{
				mylist.RemoveAt(id);
				result = true;
			}			
			catch(Exception ex)
			{
				return result;
			}

			return result;
		}

		public static void Main(string[] args)
		{	

			Console.Write("Please enter no. of videos to add to collection : ");
			int NoOfVideos = int.Parse(Console.ReadLine());
			AddVideos(NoOfVideos);
			Console.Clear();

			Console.WriteLine("Entering Video Retrieval Section...");

			Console.WriteLine("Press any key to continue..");
			Console.ReadKey();			
			
			//To Retrieve the video by Id do this..
			Console.Write("Please enter Id for the video :");
			int videoId = Convert.ToInt32(Console.ReadLine());

			if( CheckVideoExists(videoId) == true )
			{
				Console.WriteLine("The video path is : " + GetVideoPath(videoId);
				
				Console.Write("Do you wish to remove the video from the list (Y/N) : ");
				string answer = Console.ReadLine();	
			
				switch(answer)
				{
					case "Y" :
						if(RemoveVideo(videoId)==true)
						{
							Console.WriteLine("Video successfully removed from the list.");
						}
						break;
					case "N" :
						Console.WriteLine("Thank You for using Video Collections!!");
						break;	
					default :
						Console.WriteLine("Wrong option!!");
						break;
				}
			} 						
			else
			{
				Console.WriteLine("Sorry!! The video does not exists!!");
			}
		}
	}

	class Video
    	{
	        private string id;
	        private string Path;

	        public Video(string id, string Path)
	        {
        	    this.MyPath = Path;
	            this.Myid = id;
        	}


	        public string Myid
        	{
                    get{return id;}
            	    set{ id = value;}
        	}
        	public string MyPath
        	{
            	    get { return Path; }
            	    set { Path = value; }
        	}
	}
}

Open in new window

Sorry I apologize the above code has a few errors. Here is the correct code :
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace CollectionClasses
{
	public class CollectionClass
	{
		static List<object> mylist = new List<object>();
		public CollectionClass()
		{
			//Default Constructor
			
		}		
		
		public static void AddVideo(int id,string path)
		{
			Video video = new Video(id,path);
			mylist.Add(video);
			
		}

		public static bool CheckVideoExists(int id)
		{
			bool result = false;
			Video video = null;
			foreach(object o in mylist)
			{
				video = (Video)o;
				if(video.Myid == id)
				{
					result = true;	
				}
			}
			return result;
		}		
		
		public static string GetVideoPath(int id)
		{
			string path = "";
			Video video = null;
			foreach(object o in mylist)
			{
				video = (Video)o;
				if(video.Myid == id)
				{
					path = video.MyPath;	
				}
			}
			return path;
		}

		public static void AddVideos(int NoOfVideos)
		{			
			int j = 0;
			while(j<NoOfVideos)
			{
				int id = j+1;
				AddVideo(j,@"C:\MyVideos\video"+id.ToString()+".avi");
                                j++; 		
			}			
		}		

		public static bool RemoveVideo(int id)
		{
			bool result = false;
			try
			{
				mylist.RemoveAt(id);
				result = true;
			}			
			catch(Exception)
			{
				return result;
			}

			return result;
		}

		public static void Main(string[] args)
		{	

			Console.Write("Please enter no. of videos to add to collection : ");
			int NoOfVideos = int.Parse(Console.ReadLine());
			AddVideos(NoOfVideos);
			Console.Clear();

			Console.WriteLine("Entering Video Retrieval Section...");

			Console.WriteLine("Press any key to continue..");
			Console.ReadKey();			
			
			//To Retrieve the video by Id do this..
			Console.Write("Please enter Id for the video :");
			int videoId = Convert.ToInt32(Console.ReadLine());

			if( CheckVideoExists(videoId) == true )
			{
				Console.WriteLine("The video path is : " + GetVideoPath(videoId));
				
				Console.Write("Do you wish to remove the video from the list (Y/N) : ");
				string answer = Console.ReadLine().ToUpper();	
			
				switch(answer)
				{
					case "Y" :
						if(RemoveVideo(videoId)==true)
						{
							Console.WriteLine("Video successfully removed from the list.");
						}
						break;
					case "N" :
						Console.WriteLine("Thank You for using Video Collections!!");
						break;	
					default :
						Console.WriteLine("Wrong option!!");
						break;
				}
			} 						
			else
			{
				Console.WriteLine("Sorry!! The video does not exists!!");
			}
		}
	}

	class Video
    	{
	        private int id;
	        private string Path;

	        public Video(int id, string Path)
	        {
        	    this.MyPath = Path;
	            this.Myid = id;
        	}


	        public int Myid
        	{
                    get{return id;}
            	    set{ id = value;}
        	}
        	public string MyPath
        	{
            	    get { return Path; }
            	    set { Path = value; }
        	}
	}
}

Open in new window

Here I have used some hard coded paths for videos in the list.. But you can modify the code in such a way that the path is set by the user for each video that is being added to the mylist List<object>'s object. By using the following changes in the code :  
Just replace this method :
public static void AddVideos(int NoOfVideos)
                {                      
                        int j = 0;
                        while(j<NoOfVideos)
                        {
                                int id = j+1;
                                AddVideo(j,@"C:\MyVideos\video"+id.ToString()+".avi");
                                j++;            
                        }                      
                }    

With This one :
public static void AddVideos(int NoOfVideos)
                {                       
                        int j = 0;
                        string path = "";
                        while(j<NoOfVideos)
                        {
                                int id = j+1;
                                Console.Write("Please enter path for video"+id.ToString()+" : ");
                                path = Console.ReadLine();  
                                AddVideo(id,path);
                                j++;            
                        }                       
                }

Open in new window


The path of the videos would be then set by user for each of the values..
Here is the optimized code version for you :  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace CollectionClasses
{
        public class CollectionClass
        {
                static List<object> mylist = new List<object>();
                public CollectionClass()
                {
                        //Default Constructor
                        
                }               
                
                public static void AddVideo(int id,string path)
                {
                        Video video = new Video(id,path);
                        mylist.Add(video);
                        
                }

                public static bool CheckVideoExists(int id)
                {
                        bool result = false;
                        Video video = null;
                        foreach(object o in mylist)
                        {
                                video = (Video)o;
                                if(video.Myid == id)
                                {
                                        result = true;  
                                        break;
                                }
                        }
                        return result;
                }               
                
                public static string GetVideoPath(int id)
                {
                        string path = "";
                        Video video = null;
                        foreach(object o in mylist)
                        {
                                video = (Video)o;
                                if(video.Myid == id)
                                {
                                        path = video.MyPath;  
                                        break;
                                }
                        }
                        return path;
                }

                public static void AddVideos(int NoOfVideos)
                {                       
                        int j = 0;
                        string path = "";
                        while(j<NoOfVideos)
                        {
                                int id = j+1;
                                Console.Write("Please enter path for video"+id.ToString()+" : ");
                                Console.WriteLine();
                                path = Console.ReadLine();  
                                AddVideo(id,path);
                                j++;            
                        }                       
                }               

                public static bool RemoveVideo(int id)
                {
                        bool result = false;
                        try
                        {
                                mylist.RemoveAt(id);
                                result = true;
                        }                       
                        catch(Exception)
                        {
                                return result;
                        }

                        return result;
                }

                public static void Main(string[] args)
                {       

                        Console.Write("Please enter no. of videos to add to collection : ");
                        int NoOfVideos = int.Parse(Console.ReadLine());
                        AddVideos(NoOfVideos);
                        Console.Clear();

                        Console.WriteLine("Entering Video Retrieval Section...");

                        Console.WriteLine("Press any key to continue..");
                        Console.ReadKey();                      
                        
                        //To Retrieve the video by Id do this..
                        Console.Write("Please enter Id for the video :");
                        int videoId = Convert.ToInt32(Console.ReadLine());

                        if( CheckVideoExists(videoId) == true )
                        {
                                Console.WriteLine("The video path is : " + GetVideoPath(videoId));
                                
                                Console.Write("Do you wish to remove the video from the list (Y/N) : ");
                                string answer = Console.ReadLine().ToUpper();   
                        
                                switch(answer)
                                {
                                        case "Y" :
                                                if(RemoveVideo(videoId)==true)
                                                {
                                                        Console.WriteLine("Video successfully removed from the list.");
                                                }
                                                break;
                                        case "N" :
                                                Console.WriteLine("Thank You for using Video Collections!!");
                                                break;  
                                        default :
                                                Console.WriteLine("Wrong option!!");
                                                break;
                                }
                        }                                               
                        else
                        {
                                Console.WriteLine("Sorry!! The video does not exists!!");
                        }
                }
        }

        class Video
        {
                private int id;
                private string Path;

                public Video(int id, string Path)
                {
                    this.MyPath = Path;
                    this.Myid = id;
                }


                public int Myid
                {
                    get{return id;}
                    set{ id = value;}
                }
                public string MyPath
                {
                    get { return Path; }
                    set { Path = value; }
                }
        }
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial