C#查找数组中相同的项并合并

这篇博客探讨了如何使用C#处理数组,找到具有相同ID的项并将其值合并。通过创建一个二维字符串数组,利用List来存储,并通过自定义函数SumString实现合并。示例代码展示了如何遍历并打印出具有相同ID的所有项。
优快云 问题帖:查找数组中相同的项并合并.C#这个真心没SQL方便.哈哈.可能不懂LINQ吧.求指导.
http://topic.youkuaiyun.com/u/20121024/20/e395374b-176e-4f4e-899e-e360e6aa72df.html?87994  
按SQL中的办法.传一个ID.写个函数合并值.用C#实现如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SumString
{
    class Program
    {
       static string[,] str = new string[,] { { "1", "aaa" }, { "1", "bbb" }, { "2", "ccc" }, { "2", "ddd" }, 
                                                { "3", "uuu" }, { "1", "eee" }, { "4", "aaa" }, { "4", "qqq" } };
       static List<string[,]> list = new List<string[,]>();
       static List<string> listid = new List<string>();
        
        static void Main(string[] args)
        {
            Addlist();
            foreach (string[,] str in list)
            {
                if (!listid.Contains(str[0, 0]))
                {
                    if(SumString(str).TrimEnd(new char[]{','}).Contains(","))
                    Console.WriteLine("{0}--{1}", str[0, 0], SumString(str).TrimEnd(new char[]{','}));
                }
                
                listid.Add(str[0,0]);
                              
            }
            Console.ReadKey();
            
        }
        public static string SumString(string [,] para)
        {
            string str="";
            foreach (string[,] s in list)
            {
                if (s[0, 0] == para[0,0])
                {
                    str += s[0, 1] + ",";
                }
            }
            return str;
        }
        public static void Addlist( )
        {
            string[,] tempstr = new string[1, 2];
            for (int i = 0; i < str.GetLength(0); i++)
            {
                tempstr = new string[1, 2];
                for (int j = 0; j < str.GetLength(1); j++)
                {
                    if(j==0)
                    tempstr[0, 0] = str[i, j];
                    else
                    tempstr[0, 1] = str[i, j];
                  
                }
                list.Add(tempstr);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值