日期:2014-05-17  浏览次数:20749 次

数组问题二
第一组 名字和数字对应
string[] name={"张三","李四"};
int[] num={10,20};
第二组 名字和数字对应
string Oname={"张三","王五"};
int[] Onum={20,20};

两组合并为:就是同名的数值相加,不同名罗列
得到如下数组:

string AllNames={“张三”,"李四","王五"}
int []sum={30,20,20};
针对合并后的数组,数组已合并
http://topic.csdn.net/u/20120919/17/15b17d59-aace-4003-9b3b-29cfd4cc6bb5.html
以string AllNames={“张三”,"李四","王五"}为参照
对第一组 第二组数据进行如下操作
第一组 int[]num={10,20,0};(name数组中没有张三那么num为0)
第二组int[]Onum={20,0,20};(Oname数组中没有李四那么Onum为0)
请问各位该如何操作 


------解决方案--------------------
不还是循环吗?楼主应该自己试着循环写下,没啥难度的。
------解决方案--------------------
C# code
  
只写了一个,,
          List<int> age = new List<int>();
            for (int i = 0; i < AllNames.Count; i++)
            {
                if (Oname.Contains(AllNames[i]))
                {
                    for (int j = 0; j < Oname.Count(); j++)
                    {
                        if (AllNames[i] == Oname[j])
                        {
                            age.Add(Onum[j]);
                            break;
                        }
                    }
                }
                else
                {
                    age.Add(0);
                }
            }

------解决方案--------------------
原理其实是一样的
------解决方案--------------------
C# code

void Main()
{
    string[] name={"张三","李四"};
    int[] num={10,20};
    
    string[] Oname={"张三","王五"};
    int[] Onum={20,20};
    
    string[] AllNames={"张三","李四","王五"} ;

  var a1=from n in name.Select((x,i)=>new {x,i})
            join u in num.Select((y,i)=>new{y,i})
            on n.i equals u.i
            select new {n.x,u.y};
            
  var a2=from n in Oname.Select((x,i)=>new {x,i})
            join u in Onum.Select((y,i)=>new{y,i})
            on n.i equals u.i
            select new {n.x,u.y};
  
   var query= a1.Concat(a2).GroupBy(s=>s.x).Select(s=>new {s.Key,i=s.Sum(z=>z.y)});
              
   num=(from q in query
       join n in name
       on q.Key equals n into t
       from n in t.DefaultIfEmpty()
       select n==null?0:q.i).ToArray();
   
   Onum=(from q in query
       join n in Oname
       on q.Key equals n into t
       from n in t.DefaultIfEmpty()
       select n==null?0:q.i).ToArray();
   
 
}

------解决方案--------------------
C# code

//更正一下:
   num=(from q in query
       join n in a1
       on q.Key equals n.x into t
       from n in t.DefaultIfEmpty()
       select n==null?0:n.y).ToArray();
   
   Onum=(from q in query
       join n in a2
       on q.Key equals n.x into t
       from n in t.DefaultIfEmpty()
       select n==null?0:n.y).ToArray();