Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to use Linq select new to create a new data structure fro string array in C#

2 Answers

0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static int snum;
        static int GetNum(string s)
        {
            return string.IsNullOrEmpty(s) ? -999 : snum++;
        }
        static void Main(string[] args)
        {
            string[] array = { "c1", "c2", "", "c3" };

            var result = from element in array
                         select new { str = element, num = GetNum(element) };

            foreach (var part in result)
                Console.WriteLine(part);

            Console.WriteLine();

            foreach (var part in result)
            {
                string s = part.str;
                int num = part.num;

                Console.WriteLine("s = {0}, num = {1}", s, num);
            }
        }
    }
}


/*
run:

{ str = c1, num = 0 }
{ str = c2, num = 1 }
{ str = , num = -999 }
{ str = c3, num = 2 }

s = c1, num = 3
s = c2, num = 4
s = , num = -999
s = c3, num = 5

*/

 



answered Mar 4, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] array = { "c#", "c", "c++", "java", "python" };
            int n = 87;

            var html = from item in array
                       select new { Html = "<h>" + item + "</h1><br />", knowledge = n++ };

            foreach (var value in html)
            {
                Console.Write(value.Html);
                Console.WriteLine(" " + value.knowledge);
            }
        }
    }
}


/*
run:

<h>c#</h1><br /> 87
<h>c</h1><br /> 88
<h>c++</h1><br /> 89
<h>java</h1><br /> 90
<h>python</h1><br /> 91

*/

 



answered Mar 4, 2017 by avibootz
...