日期:2014-05-18  浏览次数:20897 次

求一能够从一数组中提出相同元素的函数,在线等!请各位高手指点一二,小弟刚开始学,还请各位老师赐教!
要求!:
  比如此函数名字为:bindGrid(string [],int i)
  参数string []即表示数组,i呢表示string []数组的元素相同的个数!
  例如:bindGrid(string [],5);即提取这个string []数组中出现5次的元素;
  请各位给个例子!
  拜托!

------解决方案--------------------
可以在数据查询的时候直接做。
或你自己写一个类似count(*) ... group by ... having count(*)=5 的方法。


C# code

    static string GetRepeatedElement(string[] strs, int repeats)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>();
        foreach (string s in strs)
        {
            if (dict.ContainsKey(s)) dict[s]++;
            else dict[s] = 1;
        }

        foreach (string s in dict.Keys)
        {
            if (dict[s] == repeats) return s;
        }
        return null;
    }

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

private string[] bindGrid(string[] array,int i)
{
    HashTable ht = new HashTable();
    foreach(string s in array)
    {
        if(ht.ContainsKey(s))
            ht[s]=Convert.ToInt32(ht[s])+1;
        else
            ht.Add(s,1);
    }
    List<string> list=new List<string>();
    IDictionaryEnumerator ide = ht.GetEnumerator();
    while(ide.MoveNext())
    {
        if(ide.Value.ToString()==i)
            list.Add(ide.Value.ToString());
    }
    string[] result= list.ToArray();
    return result;
}

------解决方案--------------------
string[] asa = new string[] {"1","1","2","1","3","3","1","5","3","3","3","3","3" }; 
bindGrid(asa,5); 

private static void bindGrid(string[] n,int max) 

int count=0; 
for (int i = 0; i < n.Length;i++ ) 
{
for (int j = i + 1; j < n.Length;j++ ) 

if (count-1 > max) 

Console.Write(n[i].ToString()); 
Console.Read(); 

else 

if (n[i].Equals(n[j])) count++; 



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

        string[] str = new string[] { "a", "b", "a", "c", "d", "e", "c", "a" ,"e","a","c","c","c","a"};
        public System .Collections .ArrayList  bindGrid(string[] str, int i)
        {
            int counter=0;         
            System.Collections.ArrayList alist = new System.Collections.ArrayList();
            for (int j = 0; j < str.Length; j++)
            {
                counter = 0;
                for (int k = 0; k < str.Length; k++)
                {
                    if (str[j] == str[k])
                        counter++;
                }

                if (counter == i&& alist .IndexOf (str [j])<0)//滤除相同元素
                    alist.Add(str[j]);
                

            }
            return alist;           

        }

------解决方案--------------------
返回string[] 的话可参考5楼的方式.
return (string [])alist.ToArray(typeof(string));

------解决方案--------------------