如何在结果字符串数据中添加字符串

本文关键字:字符串 数据 添加 结果 | 更新日期: 2023-09-27 18:01:09

我有一个数据库值

    ╔══════════╦════════════╦═════════════╗
    ║ SatuanID ║  Address   ║ ParentAddr  ║
    ╠══════════╬════════════╬═════════════╣
    ║  100     ║     1      ║      0      ║
    ║  101     ║     2      ║      1      ║
    ║  201     ║     4      ║      2      ║
    ║  102     ║     5      ║      1      ║
    ║  202     ║     6      ║      2      ║
    ║  203     ║     7      ║      5      ║
    ╚══════════╩════════════╩═════════════╝

这是我将数据加载到字符串的代码

public string child_list, myStr, ipList, childAdd, sub_child, sprtChild;
string sqlChild = "";
sqlChild = string.Format("select Address ,IpSlave , ( Select COUNT (*) From SatuanKawan where ParentAddr = 1) AS Count From SatuanKawan where ParentAddr = 1");
//         sql = string.Format("select * from SatuanKawan");
DataTable dtChild = CGlobalVar.dbaseBMSOps.GetDataTable(sqlChild);
List<string> list = new List<string>();
List<string> listIp = new List<string>();
List<string> listSubChild = new List<string>();
foreach (DataRow rowChild in dtChild.Rows)
{
    count = (string)rowChild["Count"].ToString();
    childAdd = (string)rowChild["Address"].ToString();
    list.Add(rowChild["Address"].ToString());
    listIp.Add(rowChild["IpSlave"].ToString());
    string sqlSubChild = "";
    sqlSubChild = string.Format("select Address From SatuanKawan where ParentAddr = {0}", childAdd);
    DataTable dtSubChild = CGlobalVar.dbaseBMSOps.GetDataTable(sqlSubChild);
    foreach (DataRow rowSubChild in dtSubChild.Rows)
    {
        listSubChild.Add(rowSubChild["Address"].ToString());
    }
}
sub_child = string.Join(",", listSubChild.ToArray());

现在childAdd值为25

子代值4,6,7

我再次使用foreach,因为我希望结果子生成值为+4,6_+7_

字符串"+"表示:

在查询"select Address From SatuanKawan where ParentAddr = {0}", childAdd中childAdd值为25

因此该值为4,67

字符串","表示子项之间的分隔添加值

因此"+">平均+4,6_+7_

字符串"_">在4,6和7 之间是分开的

因此取值结果为+4,6_+7_

如何使字符串subChild结果为+4,6_+7_

如何在结果字符串数据中添加字符串

这对我有效:

var sql = "SELECT Address, IpSlave, ParentAddr FROM SatuanKawan;";
using (var dt = CGlobalVar.dbaseBMSOps.GetDataTable(sql))
{
    var data =
        dt.Rows
            .Cast<DataRow>()
            .Select(dr => new
            {
                Address = dr["Address"].ToString(),
                IpSlave = dr["IpSlave"].ToString(),
                ParentAddr = dr["ParentAddr"].ToString(),
            })
            .ToArray();
    var lookUp = data.ToLookup(x => x.ParentAddr);
    sub_child =
        String.Join("",
            lookUp["1"]
                .Select(x => String.Format("+{0}_",
                    String.Join(",",
                        lookUp[x.Address]
                            .Select(y => y.Address)))));
}

我从你的数据中得到的结果是:

+4,6_+7_

我不确定我是否完全理解你的问题,但在我看来,你所需要做的就是用">+"替换sub_child字符串中","的最后一个实例,然后在字符串开头加一个"+",在结尾加一个">"。

换句话说,在张贴的代码末尾添加以下代码:

int index = sub_child.LastIndexOf(",");
sub_child = String.Format("+{0}_", sub_child.Remove(index, 1).Insert(index, "_+));