小编And*_*yev的帖子

字典中的ToString c#

我有一个Dictionary<int, string>c#,我需要一种方法来创建一个字符串,其内容与格式"key1-value1, key2-value2"等.

我是c#的新手,所以我创建了以下功能来实现这个目标:

private string buildString(Dictionary<int, string> info)
{
    string result = "";
    int i = 1;
    foreach (KeyValuePair<int, string> pair in info)
    {
        if (i < info.Count)
        {
            result += pair.Key + "-" + pair.Value + ",";
        }
        else
        {
            result += pair.Key + "-" + pair.Value;
        }
        i++;
    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

但是,这个功能是有效和冗长的.我知道C#有String.format,但我不确定是否以及如何使用它.

有没有更好的方法以更有效和更简洁的方式实现相同的输出?如果是这样的话?

c# string dictionary

1
推荐指数
1
解决办法
399
查看次数

C#Mysql连接必须有效并且打开

首先:我在不使用oop的情况下运行代码.我在同一个类中声明了所有变量,并在将查询传递给db之前和之后打开/关闭了连接.那很有效!现在有了一些新的经验,我试图将我的代码分成不同的类.现在它不再工作了.

它告诉我"连接必须有效且开放".足够的文字,这是我目前的代码:


Services.cs

public static MySqlConnection conn // Returns the connection itself
        {
            get
            {
                MySqlConnection conn = new MySqlConnection(Services.ServerConnection);
                return conn;
            }
        }

public static string ServerConnection // Returns the connectin-string
        {
            get
            {    
                return String.Format("Server={0};Port=XXXX;Database=xxx;Uid=xxx;password=xxXxxXxXxxXxxXX;", key);
            }
        }

public static void DB_Select(string s, params List<string>[] lists)
        {
            try
            {
                MySqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                string command = s;
                cmd.CommandText = command;
                MySqlDataReader sqlreader = cmd.ExecuteReader();
                while (sqlreader.Read())
                {
                    if (sqlreader[0].ToString().Length > 0)
                    {
                        for (int i …
Run Code Online (Sandbox Code Playgroud)

c# mysql connection database-connection

1
推荐指数
1
解决办法
5380
查看次数

WebAPI自动进行身份验证所需的弹出窗口

Webapi响应状态码401时,如何禁用“需要身份验证”弹出窗口?


在此处输入图片说明


那是我的webapi配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        //config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

asp.net authentication asp.net-mvc asp.net-web-api asp.net-web-api2

1
推荐指数
1
解决办法
1584
查看次数

MsSQL将字符串转换为DateTime

为什么在MsSQL中,几毫秒会被舍入到下一个?例如:

SELECT CONVERT(datetime, '2006-04-25 15:50:59.996', 120)
Run Code Online (Sandbox Code Playgroud)

产生

2006-04-25 15:50:59.997
Run Code Online (Sandbox Code Playgroud)

sql-server datetime rounding

1
推荐指数
1
解决办法
105
查看次数

无法访问的代码在按钮单击事件上检测到c#

下午stackoverflow成员我是c#的新手,下面的图片是单击按钮时在标签上显示文本的示例,但我继续收到无法访问的代码错误

我声明的代码:

在此输入图像描述

c# monodevelop

1
推荐指数
1
解决办法
166
查看次数

C#程序使用NPOI编辑excel(.xls)的单元格值不起作用

我编写了下面的程序,使用NPOI编辑excel文件(.xls)的单元格值,程序运行时没有错误或异常但是值没有得到更新

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.IO;
 using System.Web;
 using NPOI.XSSF.UserModel;
 using NPOI.XSSF.Model;
 using NPOI.HSSF.UserModel;
 using NPOI.HSSF.Model;
 using NPOI.SS.UserModel;
 using NPOI.SS.Util;
 namespace Project37
 {
    class Class1
    {
        public static void Main()
        {
            string pathSource = @"C:\Users\mvmurthy\Desktop\abcd.xls";
            FileStream fs = new FileStream(pathSource, FileMode.Open, FileAccess.ReadWrite); 
            HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);
            HSSFSheet sheet = (HSSFSheet)templateWorkbook.GetSheet("Contents");
            HSSFRow dataRow = (HSSFRow)sheet.GetRow(4);
            dataRow.Cells[2].SetCellValue("foo");
            MemoryStream ms = new MemoryStream();
            templateWorkbook.Write(ms);
            ms.Close();
        }     
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# excel npoi

1
推荐指数
1
解决办法
3003
查看次数

如何在Array中获取Dictionary的键和值?

我加了一些key,value字典的array,现在当我试图让我得到了一些错误的所有对:

这是代码:

protected void Button1_Click(object sender, EventArgs e)
{
    if (DropDownList1.SelectedValue.ToString() == "January")
    {
        Dictionary<string, int>[] temperatures = new Dictionary<string, int>[2];
        temperatures[0]=new Dictionary<string, int>();
        temperatures[1]=new Dictionary<string, int>();
        temperatures[0].Add("Day1",22);
        temperatures[1].Add("Day2",23);

        foreach (KeyValuePair<string,int> temperture in temperatures[])
        {
            Label1.Text = string.Format("at {0} the temperture is {1} degree", temperture.Key, temperture.Value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在错误或问题是这一行:

foreach (KeyValuePair<string,int> temperture in temperatures[])
Run Code Online (Sandbox Code Playgroud)

如果我写,temperatures[]我收到错误消息:

语法错误,值预期
索引器有1个参数,但它调用0参数()

如果我添加一个像temperatures[0]或的索引temperatures[1],我只得到第一或第二项的关键和值,但不是全部.

我该怎么办?

.net c# arrays

1
推荐指数
1
解决办法
1777
查看次数

C#:System.Data.dll中发生未处理的类型'System.Data.SqlClient.SqlException'的异常

我已经查看了关于这个主题的类似问题,发现没有一个可以与我自己的问题进行足够密切的比较.有许多不同的方法可以触发相同的异常.

我是C#的新手,正在开发一个简单的登录表单,它将用户信息存储在数据库中,然后根据请求检索它.

在调试模式下,抛出异常的行是:

cmd.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)

以前的运行没有抛出这个错误,只有当我添加一个guid或者开始尝试哈希我的密码时.

更多信息:'必须声明标量变量"@Userguid".'

我看了一遍,又一次得到了不同的答案,例如有些人认为它与连接字符串有关,而且对于他们的记者来说很可能是 - 但对我来说,我之前没有遇到任何麻烦,所以似乎不太可能.

这是我的按钮点击事件,抛出异常:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        CheckUserInput();
        CheckPassInput(); 

        //Can we create the account?
        if (canProceedUserPass == true && canProceedPass == true)
        {
            //Add username and password to my SqlDb table 'Users'. 
            Username = NewUsername.Text;
            Password = NewPassword.Password.ToString();
            Guid userGuid = System.Guid.NewGuid();

            string hashedPassword = Security.HashSHA1(Password + userGuid.ToString());

            SqlConnection con = new SqlConnection(connectionstring);
            using (SqlCommand cmd = new SqlCommand("INSERT INTO [Users] VALUES (@Username, @Password, @Userguid)", con))
            {
                cmd.Parameters.AddWithValue("@username", Username);
                                                       //HashSHA1 …
Run Code Online (Sandbox Code Playgroud)

c# variables scalar guid login

0
推荐指数
1
解决办法
2万
查看次数

迭代通过对象数组

请考虑X是一个对象数组.说对象[10].对象数组的元素表示不同的值,例如,对象[1]是学生名,对象[2]是生日,对象[3]是地址,依此类推.

以下是我试图将这些值拉入相应变量的方式,这是我进一步处理所需要的

string studentName;
string birthDate;
string address;

IEnumerable<object> collection = (IEnumerable<object>)X;

int counter = 0;
foreach (object obj in collection)
{
   if (counter == 0)
      studentName = obj.ToString();
   if (counter == 1)
      birthDate = obj.ToString();
   if (counter == 2)
      address = obj.ToString();
   ...
   counter++;
}
Run Code Online (Sandbox Code Playgroud)

这是将对象数组的值转换为单个变量的正确方法吗?有些事情感觉不对劲.

谢谢

.net c# arrays

0
推荐指数
1
解决办法
50
查看次数

为什么我需要在自联接中使用别名?

我正在学习SQL,而且恰好让我感到困惑:

我有一张1柱(boys.boy),而男孩是varchar.

SELECT boys.boy, boys.boy 
FROM boys 
LEFT JOIN boys 
  ON length(boy) > length(boy)
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样做?这会打破一些不变量,或者为什么发明者明确地引入了"自联合"?

换句话说,这是有效的("自我加入"):

SELECT b1.boy, b2.boy 
FROM boys AS b1 
INNER JOIN boys AS b2 
  ON length(b1.boy) > length(b2.boy)
Run Code Online (Sandbox Code Playgroud)

神奇之处在于别名(AS ......).

sql join

0
推荐指数
1
解决办法
910
查看次数