Solved

Converting Generic Lists to Strings using C#

Posted on 2006-11-29
3
1,051 Views
Last Modified: 2007-12-19
Let's say I have two generic lists: one is a g-list of integers (List<int>) and the other is of a custom class (List<StoredProcedureInfo>).  First, I want to convert the list of integers to a comma-delimited string:

=================================
List<int> integerList = new List<int>();
integerList.Add(4);
integerList.Add(132);
integerList.Add(36);
// How do I retrieve the values in [integerList] as a comma-delimited string?
=================================


Let's say my custom class, StoredProcedureInfo, has four properties: ID (int), Name (string), Text (string), Checked (bool).  Is there an easy way to get all of the ID property values in List<StoredProcedureInfo> as a comma-delimited string?


-= DeathToSpam =-
0
Comment
Question by:deathtospam
  • 2
3 Comments
 
LVL 18

Accepted Solution

by:
Ravi Singh earned 500 total points
Comment Utility
Hi, you can use the following method, it accepts a generic List and a string indicating the property to get the underlying data for CSVformat (see example below):

        private string GetCSVStringFromList<T>(List<T> list, string property)
        {
            string csv = string.Empty;

            if (property == null || property == string.Empty)
            {
                foreach (T item in list)
                    csv += item + ",";
            }
            else
            {
                try
                {
                    foreach (T item in list)
                        csv += item.GetType().GetProperty(property).GetValue(item, null) + ",";
                }
                catch
                {
                    return null;
                }
            }
           
            return (csv == string.Empty) ? null : csv.TrimEnd(',');
        }

To get a CSV formatted string of your integer list using above method:

      string integerListCSV = GetCSVStringFromList(integerList, null);

To get a CSV formatted string of your ID properties in a List<StoredProcedureInfo>:

      string idListCSV = GetCSVStringFromList(myStoredProcedureList, "ID");

      if (idListCSV != null)
      {
               //csv string was constructed ok...
      }

The method returns null if an error occurrs when using reflection to get the property values and also when the input list is empty.
0
 
LVL 9

Author Comment

by:deathtospam
Comment Utility
That's what I'm looking for.  But there's no built-in method of a generic list that offers the same functionality, is there?


-= DeathToSpam =-
0
 
LVL 18

Expert Comment

by:Ravi Singh
Comment Utility
Hi, not that I'm aware of... the String.Join allows you to create a CSV string by specifying a delimiter and a string array whose values will be concatenated into one string (seperated by the delim you specify as the first param)... but there doesnt seem to be a prewritten method that you can use for this type of functionality with generic lists... let alone generic lists with a specific property of the underlying type (like your ID property).


Hope this helps!
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Email Body 4 45
C# primary key 9 53
c# code 19 55
bulid json format 3 15
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now