CSharp - Store element of different type from the input sequence element type in Dictionary

Introduction

We provide a lambda expression that concatenates the firstName and lastName into a string.

The concatenated string becomes the value stored in the Dictionary.

Although our input sequence element type is Student, our element data type stored in the dictionary is string.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w  ww .j a  va  2 s . co  m*/
{
    static void Main(string[] args)
    {
        Dictionary<int, string> eDictionary = Student.GetStudentsArray()
          .ToDictionary(k => k.id,
                        i => string.Format("{0} {1}",   //  elementSelector
                          i.firstName, i.lastName));

        string name = eDictionary[2];
        Console.WriteLine("Student whose id == 2 is {0}", name);
    }
}

class Student
{
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student { id = 1, firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student { id = 2, firstName = "Windows", lastName = "Python" });
        al.Add(new Student { id = 3, firstName = "Application", lastName = "HTML" });
        al.Add(new Student { id = 4, firstName = "David", lastName = "Visual" });
        al.Add(new Student { id = 101, firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student[] GetStudentsArray()
    {
        return ((Student[])GetStudentsArrayList().ToArray());
    }
}

Result

Related Topic