Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Converting Generic Lists to Strings using C#

Posted on 2006-11-29
3
Medium Priority
?
1,057 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 18

Accepted Solution

by:
Ravi Singh earned 2000 total points
ID: 18040602
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
ID: 18046540
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
ID: 18046598
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

730 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