如何使用foreach语句创建Dictionary

时间:2014-12-06 04:27:23

标签: c# dictionary foreach

我有一个模型用于某些任务,在每个任务中我必须写下客户端的名称, 现在我有另一个客户模型,包含他们的ID,姓名,地址和电话号码。 我可以手动创建客户,但是当我创建任务时,我应该有一个包含我创建的每个客户的下拉列表

我很难向你解释......我知道我必须创建一个词典,并用foreach将这些词典中的客户添加起来。能通过向我展示一些例子来帮助我吗? 如果您需要更多详细信息,请告诉我

欣赏帮助

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace TaskManager.Models
{
    public class Client
    {
        public int id { get; set; }
        public string Nom { get; set; }
        public string Adresse { get; set; }
        public int NumeroTelephone { get; set; }

        public static List<Client> GetList()
        {
            string cStr = ConfigurationManager.ConnectionStrings["ListTask"].ConnectionString;
            using (SqlConnection cnx = new SqlConnection(cStr))
            {
                string requete = "SELECT * FROM TableClient";
                SqlCommand cmd = new SqlCommand(requete, cnx);
                cmd.CommandType = System.Data.CommandType.Text;
                try
                {
                    cnx.Open();
                    SqlDataReader dataReader = cmd.ExecuteReader();
                    List<Client> clientList = new List<Client>();
                    while (dataReader.Read())
                    {
                        Client t = new Client();
                        t.Nom = (string)dataReader["Nom"];
                        t.Adresse = (string)dataReader["Adresse"];
                        t.NumeroTelephone = (int)dataReader["NumeroTelephone"];
                        clientList.Add(t);
                    }
                    dataReader.Close();
                    return clientList;
                }
                finally
                {
                    cnx.Close();
                }
            }

        }
        public static Client FindOne(int id)
        {
            string cStr = ConfigurationManager.ConnectionStrings["mycnx"].ConnectionString;
            using (SqlConnection cnx = new SqlConnection(cStr))
            {
                string requete = "SELECT * FROM TableClient WHERE id = " + id;
                SqlCommand cmd = new SqlCommand(requete, cnx);
                cmd.CommandType = System.Data.CommandType.Text;
                try
                {
                    cnx.Open();
                    SqlDataReader dataReader = cmd.ExecuteReader();
                    Client t = new Client();
                    while (dataReader.Read())
                    {
                        t.id = (int)dataReader["id"];
                        t.Nom = (string)dataReader["Nom"];
                        t.Adresse = (string)dataReader["Adresse"];
                        t.NumeroTelephone = (int)dataReader["NumeroTelephone"];
                    }
                    dataReader.Close();
                    return t;
                }
                finally
                {
                    cnx.Close();
                }
            }
        }
        public bool SaveAsNew()
        {
            string cN = ConfigurationManager.ConnectionStrings["mycnx"].ConnectionString;

            using (SqlConnection cnx = new SqlConnection(cN))
            {
                // Utilisation de la connexion
                string requete = "INSERT INTO TableClient (Nom, Adresse, NumeroTelephone)";
                requete += "VALUES (@Nom, @Adresse, @NumeroTelephone)";

                SqlCommand cmd = new SqlCommand(requete, cnx);
                cmd.CommandType = System.Data.CommandType.Text;
                //définir les paramètres
                cmd.Parameters.Add("Nom", SqlDbType.NVarChar);
                cmd.Parameters.Add("Adresse", SqlDbType.NVarChar);
                cmd.Parameters.Add("NumeroTelephone", SqlDbType.Int);
                //donner des valeurs aux paramètres
                cmd.Parameters["Nom"].SqlValue = this.Nom;
                cmd.Parameters["Adresse"].SqlValue = this.Adresse;
                cmd.Parameters["NumeroTelephone"].SqlValue = this.NumeroTelephone;
                cnx.Open();
                cmd.ExecuteNonQuery();
                cnx.Close();
                return true;
            }
        }
        public bool Update()
        {
            string cN = ConfigurationManager.ConnectionStrings["mycnx"].ConnectionString;

            using (SqlConnection cnx = new SqlConnection(cN))
            {
                // Utilisation de la connexion
                string requete = "UPDATE Task SET ";
                requete += "Nom=@Nom,";
                requete += "Adresse=@Adresse,";
                requete += "Numero de telephone=@NumeroTelephone,";
                requete += "WHERE Id = " + this.id;

                SqlCommand cmd = new SqlCommand(requete, cnx);
                cmd.CommandType = System.Data.CommandType.Text;
                //définir les paramètres
                cmd.Parameters.Add("Nom", SqlDbType.NVarChar);
                cmd.Parameters.Add("Adresse", SqlDbType.NVarChar);
                cmd.Parameters.Add("NumeroTelephone", SqlDbType.Int);
                //donner des valeurs aux paramètres
                cmd.Parameters["Nom"].SqlValue = this.Nom;
                cmd.Parameters["Adresse"].SqlValue = this.Adresse;
                cmd.Parameters["NumeroTelephone"].SqlValue = this.NumeroTelephone;
                cnx.Open();
                cmd.ExecuteNonQuery();
                cnx.Close();
                return true;
            }

        }
        public static bool Destroy(int id)
        {
            string cN = ConfigurationManager.ConnectionStrings["mycnx"].ConnectionString;
            using (SqlConnection cnx = new SqlConnection(cN))
            {
                string requete = "DELETE FROM TableClient WHERE Id = " + id;
                SqlCommand cmd = new SqlCommand(requete, cnx);
                cmd.CommandType = System.Data.CommandType.Text;
                cnx.Open();
                cmd.ExecuteNonQuery();
                cnx.Close();
                return true;
            }
        }

这不起作用

        public static readonly Dictionary<int, string> Clients = new Dictionary<int, string>()
        {                
                       foreach C in Client.GetList()
            {Clients.Add(id, "test" }   
                    }




    }

这是一个相同的工作示例,但是我必须手动将每个项目添加到dictionnary ...基本上第一个dictionnary应该放在我创建的客户端模型上并让每个客户端进入并将它们添加到词典中...希望我不会让你觉得这太难了。

public static readonly Dictionary<int, string> Priorities = new Dictionary<int, string>
        {
            { 0, "Choisir une valeur!" },
            { 1, "1 - Pas urgent pantoute!" },
            { 2, "2 - Bah! ça serait le fun que ça soit fait un jour!" },
            { 3, "3 - Pour hier!" }
        };

1 个答案:

答案 0 :(得分:0)

您可能不希望将Clients字典声明为readonly,除非您要在静态构造函数中创建它。如果这是你想要做的,那么你必须创建一个静态构造函数:

// static dictionary of clients
public static readonly Dictionary<int, string> Clients;

// This is the static constructor for the Client class
static Client()
{
    // create and populate the Clients dictionary
    Clients = new Dictionary<int, string>();

    foreach (var c in GetList())
    {
        Clients.Add(c.id, c.Nom);
    }
}

但是,如果这样做,那么无论何时创建新记录,都必须向字典添加新项目,如果更改名称,则必须更新字典。请记住,静态构造函数是一次运行 - 首次访问Client类型时。

您可以缩短Client构造函数中的代码,使其成为单个LINQ语句:

Clients = GetList().ToDictionary(c => c.id, c => c.Nom);

看起来你真正想要的东西是按需构建字典的东西。在这种情况下,您可以使用GetClientsDictionary方法在需要时调用:

public static Dictionary<int, string> GetClientsDictionary()
{
    return GetList().ToDictionary(c => c.id, c => c.Nom);
}