简体   繁体   English

如何根据循环自动创建变量?

[英]How can I automatically create variables according to a loop?

I created a program that checks how many times an item is repeated in an array. 我创建了一个程序来检查一个项目在数组中重复多少次。

However, for every item that repeats at least twice, I want to assign it to a variable. 但是,对于每个重复至少两次的项目,我想将其分配给一个变量。 My problem is that, my list might be bigger at times or smaller. 我的问题是,我的列表有时可能更大或更小。 So I need my loop to go through and if a copy is found, to create a variable of type int and assign the number of repeats to it. 因此,我需要遍历循环,如果找到了副本,则需要创建一个int类型的变量并为其指定重复次数。 I seem to remember reading something on Java about this, but I forgot what it's called, or I'm just confused. 我似乎记得在Java上读过一些有关此的内容,但是我忘记了它的名称,否则我很困惑。 Please help. 请帮忙。 Thank you. 谢谢。

Update: I want the output to be like this: 更新:我希望输出是这样的:

(A : 20) - (B : 114) - (C : 50) - (W : 0) (A:20)-(B:114)-(C:50)-(W:0)

Currently I am trying to check if 目前,我正在尝试检查

    string[] art = new string[] {"ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600"};
    string[] cd = new string[] {"A", "B"};

    int control = 0;

    //I will fill this in the first loop below with 
    //the first letter of each item in the art array
    ArrayList firstLetter = new ArrayList ();

    //this one gets filled after the second loop ends
    ArrayList numOfLetters = new ArrayList ();

    for(int k = 0; k < art.Length; k++){ //iterate 4 times, add 1st letter
        firstLetter.Add (art[k].Substring(0, 1));
    }

    for (int j = 0; j < art.Length; j++) { //iterate 4 times 
        //check how many times a letter repeats in 'art'
        while (firstLetter.Contains (art [j].Substring (0, 1))) {
            control++; //
    }
        numOfLetters.Add ("(" + art [j].Substring (0, 1) + " " + ":" + " " + 
                control + ")");
            control = 0;
        }
    print (numOfLetters[0]);

If none of this makes sense, I would be happy to just know how I can check an arraylist for how many times a letter repeats. 如果所有这些都没有道理,那么我很乐意知道如何检查一个数组列表中字母重复的次数。

i,e; I,E;

ArrayList ABCADAEF ArrayList ABCADAEF

I want to know how I can check how many times 'A' repeats 我想知道如何检查“ A”重复多少次

I'm not quite sure what that block of code is doing, so I'll just address your last example. 我不太确定该代码块在做什么,所以我只讲最后一个例子。 First, avoid using ArrayList . 首先,避免使用ArrayList You can store any object in it, but you can't easily tell what type of object is stored in it. 您可以在其中存储任何object ,但不能轻易分辨出存储在其中的对象类型 When you get the values back out, you have to unbox them. 取回值时,必须将它们拆箱。 It's a pain to use. 使用起来很痛苦。

Instead, use a List<T> where T is a string in your sample. 而是使用List<T> ,其中T是示例中的string

List<string> letters = new List<string> {"A", "B", "C", "A", "D", "A", "E", "F"};

Group your original array by values using LINQ (letters in your case), then store the count of any values that occur at least twice. 使用LINQ(用您的字母表示)将值按原始数组分组,然后存储至少出现两次的任何值的计数。 (I modified your sample collection to have more duplicates.) (我修改了您的样本集合,使其具有更多重复项。)

There's another built in method called string.Join , which takes a collection, flattens it out to a single string, and separates all the elements of the collection by some other string ( " - " here). 还有另一个内置的方法,称为string.Join ,该方法获取一个集合,将其展平为单个字符串,然后用其他字符串(此处为" - " )将集合的所有元素分开。

var letters = new List<string> {"B", "A", "C", "A", "A", "B", "A", "B"};

var repeats = letters.GroupBy(i => i)
                     .Where(g => g.Count() >= 2)
                     .ToDictionary(t => t.Key, t => t.Count());

var output = string.Join(" - ", repeats.OrderBy(x => x.Key)
                                       .Select(x => string.Format("({0} : {1})", x.Key, x.Value)));

// output: "(A : 4) - (B : 3)"

It sounds like you might be looking for a Dictionary<T, int> . 听起来您可能正在寻找Dictionary<T, int> You didn't mention what type of items are contained in the array, so you'll want to swap out the T with whatever that type is. 您没有提到数组中包含什么类型的项目,因此您想将T换成该类型的任何东西。

A quick and dirty implementation might look something like this: 一个快速而肮脏的实现可能看起来像这样:

Dictionary<object, int> dict = new Dictionary<object, int>();
object[] objs = new object[] { ... };

for (int v = 0; v < objs.Length; v++)
{
    object obj = objs[v];

    int count = dict.TryGet(obj, out count) ? count : 0;
    dict[obj] = count + 1;
}

This sounds like CS homework, so I'm assuming that's probably what you're looking for, but if this is for production, I'd be tempted to do it with LINQ. 这听起来像CS作业,所以我假设这可能是您正在寻找的东西,但是如果这是用于生产,那么我很想用LINQ来做。

Dictionary<object, int> dict = objs.GroupBy(c => c)
                                   .ToDictionary(c => c.Key, c => c.Count());

Once you've got your dictionary, it's just a matter of checking for items with more than one as the value. 获取字典后,只需检查值是否超过一个的项目即可。 You can do that by looping through, either with a foreach or, again, with LINQ. 您可以通过使用foreach或再次使用LINQ进行遍历来实现。

This is another super quick implementation, and you might want to do it differently. 这是另一种超级快速的实现,您可能想要以不同的方式进行。 But this would capture the gist of it. 但这将抓住要点。

foreach (var v in dict.ToList())
{
    if (v.Value < 2)
        dict.Remove(v.Key);
}

Another feasible approach would be to make use of a HashSet<> , which only allows one instance of any given object at a time. 另一种可行的方法是利用HashSet<> ,它一次只允许任何给定对象的一个​​实例。

object[] objs = new object[] { ... };
HashSet<object> buffer = new HashSet<object>();
HashSet<object> repeated = new HashSet<object>();

foreach (var v in objs)
{
    if(!buffer.Add(v))
    {
        repeated.Add(v);
    }
}

Here, I loop through each item and add it to a buffer HashSet<> . 在这里,我遍历每一项并将其添加到缓冲区HashSet<> If that returns false, it means it's already been added, so it's a duplicate. 如果返回false,则表示它已被添加,因此是重复项。 At that point, I append it to yet a second HashSet<> , which would be your result. 到那时,我将其附加到第二个HashSet<> ,这将是您的结果。 I chose this over a List<> for the result because I assume you don't want duplicate reports in that, in the event of an item showing up in the array more than two times. 我选择了List<>作为结果,因为我假设您不希望重复的报告,如果某项在数组中显示两次以上。 But either works, aside from that. 但是除此之外,任何一种都可以。

Your item class: 您的物品类别:

class YourItem
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
}

Now in we fill in some list of items and process it: 现在,我们填写一些项目清单并进行处理:

// defining example item list
var items = new List<YourItem>() { 
    new YourItem() { ItemId = 1, ItemName = "FirstItem" }, 
    new YourItem() { ItemId = 1, ItemName = "FirstItem" }, 
    new YourItem() { ItemId = 2, ItemName = "SecondItem" } };

var groups = items.GroupBy(item => item.ItemId) // grouping your items by id (or how do you compare them?) to be able to count repetitions
    .Where(group => group.Count() > 1) // filtering out those that are not repeated
    .Select(group => new { Item = group.First(), Sum = group.Count() }); // selecting Item and Count for each group.

// processing the results
foreach (var group in groups)
{
    Console.WriteLine(group.Item.ItemName + " " + group.Sum);
}

Output: 输出:

FirstItem 2

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

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