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

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven