Skip to main content

Generate CSV values easily in C# , String Manipulation in C#

Suppose you are having a List<String> and you are in need to generate a Comma Separated Value (CSV) from this with single quotes attached

 

Say We need to dynamically generate a simple SQL Select statement from a Order table and the filter criteria would be like this

 

Select New ('NO') Orders, Active ('AO') Orders and Successful ('SO') Orders

Let's we have a Status Codes in a List<String>

 

The desired output

SELECT * FROM ORDERS WHERE STATUS IN ('NO', 'AO', 'SO')

 

Traditional Solution

 

TraditionalSolution(StatusCodes);

 

private static void TraditionalSolution(List<string> StatusCodes)

{

// Traditionally what we will do is

// Loop through the List and generate a SQL Statement

 

string OutputSQL = "SELECT * FROM ORDERS WHERE STATUS IN (";

 

int Count = StatusCodes.Count();

foreach (string SingleStatusCode in StatusCodes)

{

OutputSQL += "'" + SingleStatusCode + "'";

Count--;

 

// This is critial to avoid the last character comma

if (Count >= 1)

{

OutputSQL += ", ";

}

 

}

OutputSQL += ")";

 

Console.WriteLine(string.Empty);

 

Console.WriteLine(OutputSQL);

}

 

 

 

Output

 

SELECT * FROM ORDERS WHERE STATUS IN ('NO','AO','SO')

 

 

NewSolution(StatusCodes);

 

 

private static void NewSolution(List<string> StatusCodes)

{

string OutputSQL = "SELECT * FROM ORDERS WHERE STATUS IN (";

 

OutputSQL += string.Join(", ", StatusCodes.Select(X => string.Format("'{0}'", X)));

 

OutputSQL += ")";

 

Console.WriteLine(string.Empty);

 

Console.WriteLine(OutputSQL);

}

 

 

Output

 

SELECT * FROM ORDERS WHERE STATUS IN ('NO','AO','SO')

 

 

Here we are creating a list of orders and each order will contain the status codes what we have seen before,

Let’s see how to handle this List of Orders collection in the New Logic

 

    class Orders

    {

        public int OrderID { get; set; }

        public string OrderStatus { get; set; }

 

        public Orders(int pOrderID, string pOrderStatus)

        {

            OrderID = pOrderID;

            OrderStatus = pOrderStatus;

        }

    }

 

And in the Main we are calling like this

            List<Orders> LstOrders = new List<Orders>();

            LstOrders.Add(new Orders(1, "NO"));

            LstOrders.Add(new Orders(2, "AO"));

            LstOrders.Add(new Orders(3, "SO"));

           

 

            NewSolutionWithClassesInvolved(LstOrders);

 

 

 

 

 

private static void NewSolutionWithClassesInvolved(List<Orders> LstOrders)

{

string OutputSQL = "SELECT * FROM ORDERS WHERE STATUS IN (";

 

OutputSQL += string.Join(", ", LstOrders.Select(X => string.Format("'{0}'", X.OrderStatus)));

 

OutputSQL += ")";

 

Console.WriteLine(string.Empty);

 

Console.WriteLine(OutputSQL);

}

 

 

Output

 

SELECT * FROM ORDERS WHERE STATUS IN ('NO','AO','SO')

 

The Source Code is available in the following link

 

https://github.com/oneananda/C_Sharp_Examples/blob/main/String_Manipulation/Generating_CSV_Values.cs

 

YouTube Link

 

https://www.youtube.com/watch?v=6zbhH-Mn0tg

 

 

 

 

 

Comments

Popular posts from this blog

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods