c#变量在for循环之外没有得到所有的值

本文关键字:变量 for 循环 | 更新日期: 2023-09-27 18:03:52

我在字典中有两个值,但当我试图在循环外获得两个值时,我只获得一个值。locationdesc变量值正在被覆盖。有没有更好的方法来创建唯一的变量来处理这个问题

有两个键location-1和location-2。我想弄清楚如何在循环外得到这两个值。我做错了吗?

string locationDesc = "";
string locationAddress = "";
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
for (int i = 1; i <= count; i++)
{
    if (dictionary.ContainsKey("location-"+i))
    {
        string locationData = dictionary["location-"+i];
        string[] locationDataRow = locationData.Split(':');
        locationDesc = locationDataRow[0];
        locationAddress = locationDataRow[1];
    }
}
// Only getting location-2 value outside this loop since locationDesc is not unique.
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress);

What I would like to get here is get both the values like locationDesc1 and locationDesc2 instead of locationDesc

我要找的是创建locationDesc和locationAddress唯一,这样我就可以访问for循环之外的两个值。

更多解释,因为我不是很清楚:

我有一个动态表,将在前端创建。每次创建位置时,我都会创建一个cookie。例如location-1, location-2…location-n,将位置描述和位置值作为cookie中的值。我试图通过创建字典来访问后端这些值,这样我就可以将所有值分配给唯一的变量,这将使我更容易将这些值传递给api调用。我想我把一个简单的问题复杂化了,可能做错了。

我的api调用将是这样的:

<field="" path="" value=locationDesc1>
<field="" path="" value=locationDesc2>

c#变量在for循环之外没有得到所有的值

循环的问题在于,您依赖于字典中条目的位置与循环中的索引相匹配。你的第一行代码基本上就是这样的:

int count = dictionary.Count(D => D.Key.StartsWith("location-"));

这告诉我,你正在查找字典中键以"location-"开头的所有条目。那么为什么不直接这样做呢:

var values = dictionary.Where(d => d.Key.StartsWith("location-"));

并同时进行提取/字符串分割:

var values = dictionary
    .Where(d => d.Key.StartsWith("location-"))
    .Select(d => d.Item.Split(':')
    .Select(s => new 
    { 
        LocationDesc = s[0], 
        LocationAddress = s[1]
    });

这将给你一个IEnumerable的LocationDesc/LocationAddress对,你可以循环:

foreach(var pair in values)
{
    Debug.WriteLine(pair.LocationDesc);
    Debug.WriteLine(pair.LocationAddress);
}

试试这个:

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
Dictionary<string, string> values = new Dictionary<string, string>();
for (int i = 1; i <= count; i++)
{
    if (dictionary.ContainsKey("location-"+i))
    {
        string locationData = dictionary["location-"+i];
        string[] locationDataRow = locationData.Split(':');
        values.Add(locationDataRow[0],locationDataRow[1]);
    }
}
foreach (var item in values)
{
    Debug.WriteLine(item.Key + " : " + item.Value);
}

当您处理多个值时,您应该使用可以存储所有值的容器。

如果你只处理两个唯一的值,那么使用下面的代码

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
string[] locationDesc = new string[2];
string[] locationAddress = new string[2];
    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            locationDesc[i-1] = locationDataRow[0];
            locationAddress[i-1] = locationDataRow[1];
        }
    }
for (int i = 0; i <= locationDesc.Length-1; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}    

如果唯一值的数量不固定,则使用ArrayList

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
ArrayList locationDesc = new ArrayList();
ArrayList locationAddress = new ArrayList();
    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            locationDesc.Add(locationDataRow[0]);
            locationAddress.Add(locationDataRow[1]);
        }
    }
for (int i = 0; i < locationDesc.Count; i++)
{
    Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
    Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}

简单。如果您只想使用Debug显示结果。WriteLine,然后使用下面的代码

int count = dictionary.Count(D => D.Key.StartsWith("location-"));
    for (int i = 1; i <= count; i++)
    {
        if (dictionary.ContainsKey("location-"+i))
        {
            string locationData = dictionary["location-"+i];
            string[] locationDataRow = locationData.Split(':');
            Debug.WriteLine("Location Desc from dictionary is : " + locationDataRow[0]);
            Debug.WriteLine("Location Add from dictionary is : " + locationDataRow[1]);
        }
    }

目前无法在Visual Studio中准备代码,因此可能会有一些语法错误。

很难判断你想要做什么。我不会为了好玩而把你已经有的东西扔到别的东西里。如果您只是试图在循环中公开值以供另一个函数使用,则可以使用LINQ来遍历字典。如果您想要一个特定的值,只需添加一个where LINQ表达式。我相信LINQ应该在3.5以后的任何。net框架中。

public static void ApiMock(string s)
{
  Console.WriteLine($"I worked on {s}!");
}
static void Main(string[] args)
{
  var d =  new Dictionary<int, string> {
      {  1, "location-1" },
      {  2, "location-2" },
      {  3, "location-3" }
  };
  d.ToList().ForEach(x => ApiMock(x.Value));
  //I just want the second one
  d.Where(x => x.Value.Contains("-2")).ToList().ForEach(x => ApiMock(x.Value));
  //Do you want a concatenated string
  var holder = string.Empty;
  d.ToList().ForEach(x => holder += x.Value + ", ");
  holder = holder.Substring(0, holder.Length - 2);
  Console.WriteLine(holder);
}