简体   繁体   English

如何检查数组中的重复项,然后对它们的值进行处理?

[英]How to check for duplicates in an array and then do something with their values?

I have an array for example( "1:2","5:90","7:12",1:70,"29:60" ) Wherein ID and Qty are separated by a ':' (colon), what I want to do is when there's a duplicate of IDs the program will add the qty and return the new set of arrays so in the example it will become ("1:72","5:90","7:12","29:60"). 我有一个数组,例如( "1:2","5:90","7:12",1:70,"29:60" ),其中ID和数量用':'(冒号)分隔,我想做的是,当ID重复时,程序将添加数量并返回新的数组集,因此在示例中它将变为(“ 1:72”,“ 5:90”,“ 7:12” ,“ 29:60”)。

Ex.2 ( "1:2","5:90","7:12","1:70","29:60","1:5" ) becomes ( "1:77","5:90","7:12","29:60" ). "1:2","5:90","7:12","1:70","29:60","1:5""1:2","5:90","7:12","1:70","29:60","1:5" )变成( "1:77","5:90","7:12","29:60" )。

I want to solve it without using linq. 我想不使用linq来解决它。

var foo = array.Select(s => s.Split(':'))
               .GroupBy(x => x[0])
               .Select(g => 
                    String.Format(
                        "{0}:{1}",
                        g.Key,
                        g.Sum(x => Int32.Parse(x[1]))
                    )
               )
               .ToArray();

Note, it's not necessary to parse the "keys," only the values. 请注意,不必解析“键”,只需解析值。

Without LINQ: 没有LINQ:

var dictionary = new Dictionary<string, int>();
foreach (var group in array) {
    var fields = group.Split(':');
    if (!dictionary.ContainsKey(fields[0])) {
        dictionary.Add(fields[0], 0);
    }
    dictionary[fields[0]] += Int32.Parse(fields[1]);
}
string[] foo = new string[dictionary.Count];
int index = 0;
foreach (var kvp in dictionary) {
    foo[index++] = String.Format("{0}:{1}", kvp.Key, kvp.Value);
}

You have to do this manually. 您必须手动执行此操作。 Loop through each list, check the ID for each element. 遍历每个列表,检查每个元素的ID。 Put it in a Dictionary<int, int> , Dictionary<id, qt> . 将其放在Dictionary<int, int>Dictionary<id, qt> If the dictionary contains the id, add it to the value. 如果字典中包含ID,则将其添加到值中。

  1. Loop, add, check using Dictionary class. 使用Dictionary类循环,添加,检查。
(
    from raw in arr
        let splitted = raw.Split(':')
        let id = int.Parse(splitted[0])
        let qty = int.Parse(splitted[1])
        let data = new { id, qty }
        group data by data.id into grp
            let totalQty = grp.Sum(val => val.qty)
            let newStr = string.Format("{0}:{1}", grp.Key, totalQty
            select newStr
)
.ToArray()

Note that the code may contain accidental errors, as it was written in notepad. 请注意,该代码可能包含意外的错误,因为它是在记事本中编写的。

var input=new string[]{"1:2","5:90","7:12","1:70","29:60","1:5"};
var result=input
             .Select(s=>s.Split(':'))
             .Select(x=>x.Select(s=>int.Parse(s)).ToArray())
             .GroupBy(x=>x[0])
             .Select(g=>g.Key+":"+g.Sum(x=>x[1]));

I was too lazy to specify the culture everywhere. 我太懒了,无法指定各地的文化。 You probably want to do that before putting it into production, or it will fail for cultures with unusual integer representations. 您可能想在将其投入生产之前进行此操作,否则,对于具有异常整数表示形式的区域性,它将失败。

var totals=new Dictionary<int,int>
foreach(string s in input)
{
  string[] parts=s.Split(':');
  int id=int.Parse(parts[0]);
  int quantity=int.Parse(parts[0]);
  int totalQuantity;
  if(!totals.TryGetValue(id,out totalQuantity))
      totalQuantity=0;//Yes I know this is redundant
  totalQuanity+=quantity;
  totals[id]=totalQuantity;
}
var result=new List<string>();
foreach(var pair in totals)
{
  result.Add(pair.Key+":"+pair.Value);
}

If you want it without LINQ... 如果您想要不使用LINQ ...

var totalQuantities = new Dictionary<int, int>();
foreach(var raw in sourceArr) {
    var splitted = raw.Split(':');
    int id = int.Parse(splitted[0]);
    int qty = int.Parse(splitted[1]);
    if(!totalQuantities.ContainsKey(id)) {
        totalQuantities[id] = 0;
    }
    totalQuantities[id] += qty;
}

var result = new string[totalQuantities.Count];
int i=0;
foreach(var kvp in totalQuantities) {
    result[i] = string.Format("{0}:{1}", kvp.Key, kvp.Value);
    i++;
}

try this: 尝试这个:

List<string> items = new List<string>(new string[] { "1:2", "5:90", "7:12", "1:70", "29:60" });
Dictionary<string, int> dictionary = new Dictionary<string, int>();

foreach (string item in items)
{
    string[] data = item.Split(':');
    string key = data[0];

    if (!dictionary.ContainsKey(data[0]))
    {
        int value = dictionary[data[0]];
        dictionary[key] += int.Parse(data[1]);
    }
}

//Used dictionary values here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM