String interpolation: How do I make this function work with any type

Related searches

This is a function to work with lists in string interpolation. It takes a List and an inner Func, and it appends the string result of the inner Func called for each member of the list, with a separator.

So the following builds a valid start of an Insert statement...

static void Main(string[] args)
{
    var tableName = "customers";
    var cols = new List<dynamic>
    {
        new { Name = "surname"},
        new { Name = "firstname"},
        new { Name = "dateOfBirth"}
    };
    Func<List<dynamic>, Func<dynamic, string>, string, string> ForEach = (list, func, separator) =>
        {
            var bldr = new StringBuilder();
            var first = true;
            foreach (var obj in list)
            {
                if (!first)
                    bldr.Append(separator);
                first = false;
                bldr.Append(func(obj));
            }
            return bldr.ToString();
        };

    var InsertStatement = $"Insert into { tableName } ( {ForEach(cols, col => col.Name, ", ")} )";
    Console.WriteLine(InsertStatement);
    Console.ReadLine();
}

Outputs...

Insert into customers ( surname, firstname, dateOfBirth )

It works for dynamic. How do I make it work for any type? The outer Func shouldn't care about the Type in the list, it just passes it through to the inner Func.

Replace dynamic with object, or TValue with a type constraint stipulating it must be a class (where TValue : class), and call obj.ToString() instead of just obj

However, this doesn't guarantee it would "work with any type" - for that you need to know that those types all follow a contract to output the desired column name as their string representation. To get more specificity, require that your accepted types must implement some interface eg IColumnName and put that interface into the type constraint instead

String Interpolation in JavaScript, How to use template literals to perform string interplation in JavaScript (w/ examples and The expression inside the placeholder can be of any kind: You can put any expression inside the placeholder: either an operator, a function call, or even The string interpolation in TypeScript works the same way as in JavaScript:. String interpolation is a great programming language feature that allows injecting variables, function calls, arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6. String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character.

The .NET framework already gives you a generic function to achieve what you are trying to do String.Join and you can combine it with a LINQ Select statement, which will allow you to use a lambda on a generic type to select the property that you want to print. You can view the source code of these methods if you are interested as they are open source.

using System;
using System.Collections.Generic;
using System.Linq;

public class MyType
{
   public string Name { get; set; } 
}

public class Program
{
    public static void Main()
    {
        var tableName = "customers";
        var cols = new List<MyType>
        {
            new MyType { Name = "surname"},
            new MyType { Name = "firstname"},
            new MyType { Name = "dateOfBirth"}
        };

        var InsertStatement = $"Insert into { tableName } ( {String.Join(", ", cols.Select(col => col.Name))} )";
        Console.WriteLine(InsertStatement);
    }
}

String interpolation in C#, NET type formatting, check out the interactive string interpolation Select the Run button to run an example in an interactive window. You can embed any valid C# expression that returns a value in an FormattableString instance and call its ToString(IFormatProvider) method to create a culture-specific´┐Ż String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like "Hello {Name of person}, nice to meet you!", you would like to replace the placeholder for name of person with an actual name. This process is called string interpolation.

You can create the text easily like this:

var query = $"INSERT INTO {tableName}({string.Join(",", cols.Select(x=>x.Name))})";

However, if for learning purpose you are going to handle the case using a generic method, you can create a generic function like the following and then easily use a for loop and strip additional separator using TrimEnd, or as a better option, like String.Join implementation of .NET Framework get enumerator like this:

string Join<TItem>(
    IEnumerable<TItem> items, Func<TItem, string> itemTextSelecor, string separator)
{
    var en = items.GetEnumerator();
    if (!en.MoveNext())
        return String.Empty;
    var builder = new StringBuilder();
    if (en.Current != null)
        builder.Append(itemTextSelecor(en.Current));
    while (en.MoveNext())
    {
        builder.Append(separator);
        if (en.Current != null)
            builder.Append(itemTextSelecor(en.Current));
    }
    return builder.ToString();
}

And use it this way:

var tableName = "customers";
var cols = new[]
{
    new { Name = "surname"},
    new { Name = "firstname"},
    new { Name = "dateOfBirth"}
};

var InsertStatement = $"INSERT INTO {tableName} ({Join(cols, col => col.Name, ", ")})" 
    +  $"VALUES({Join(cols, col => $"@{col.Name}", ", ")})";

String interpolation, This tutorial shows you how to use the C# string interpolation feature to include Make it the current directory and run the following command from a The result of an interpolation expression can be of any data type, though. If an interpolated string has the type string, it's typically transformed into a String.Format method call. The compiler may replace String.Format with String.Concat if the analyzed behavior would be equivalent to concatenation.

String interpolation, In computer programming, string interpolation is the process of evaluating a string literal Expansion of the string usually occurs at run time. Some languages do not offer string interpolation, instead offering a standard function where one There are two main types of expand variable algorithms for variable interpolation:. String formatting or String interpolation is an important concept in any language. Printf would probably be the general implementation of how a variable of any type is formatted in a string.

Back to Basics: String Interpolation in C#, In this post I look at how string interpolation works, what the compiler Format() function for string literals, although there are some At first blush interpolated strings look like an easy way to create I find that invaluable because out of habit I tend to type concats, and I like converting them after the fact. Since ES6, if you want to do string interpolation in object keys, you will get a SyntaxError: expected property name, got '${' if you do something like: let age = 3 let obj = { `${age}`: 3 } You should do the following instead: let obj = { [`${age}`]: 3 }

String arrays provide a set of functions for working with text as data. Starting in R2017a, you can create strings using double quotes, such as str = "Greetings friend". To convert data to string arrays, use the string function.

Comments
  • You can make ForEach method generic and apply some constraints on it
  • List<T> already has a ForEach method built in. Also, you're practically inviting hackers constructing SQL this way. Read about SQL Injection.
  • You've also passed the list of objects in outer Func and inner Func to access these objects members, both functions should care about the type, otherwise dynamic is only option here
  • As an aside, string.Join(separator, list.Select(func)) means you don't need to write your own code for that...
  • var query = $"INSERT INTO {tableName}({string.Join(",", cols.Select(x=>x.Name))})";
  • OP wants to access an object members, using inner Func, ToString() doesn't work here, IMO