質問

はあるので簡単にカウントの発行数の全ての要素をリストに同じリストのC#?

のようなこと:

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

string Occur;
List<string> Words = new List<string>();
List<string> Occurrences = new List<string>();

// ~170 elements added. . . 

for (int i = 0;i<Words.Count;i++){
    Words = Words.Distinct().ToList();
    for (int ii = 0;ii<Words.Count;ii++){Occur = new Regex(Words[ii]).Matches(Words[]).Count;}
         Occurrences.Add (Occur);
         Console.Write("{0} ({1}), ", Words[i], Occurrences[i]);
    }
}
役に立ちましたか?

解決

このようなことはどうですか...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

コメントごとの編集:私はこの正義を試みます。 :)

私の例では、それはaです Func<int, TKey> 私のリストはintsだからです。だから、私はグループビーに自分のアイテムをグループ化する方法を伝えています。 FUNCにはINTがかかり、グループのキーを返します。この場合、私は取得します IGrouping<int,int> (INTによってキー化されたINTのグループ化)。私がそれを変更した場合(i => i.ToString() )たとえば、私は自分のグループ化を文字列でキーイングすることになります。 「1」、「2」、「3」でキーイングするよりも些細な例を想像できます...「1」、「2」、「3」を私の鍵に戻す関数を作るかもしれません...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

だから、それはintを取って文字列を返すための機能です...のように...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

しかし、元の質問では元のリスト値とそれがカウントされることを要求したので、整数を使用して整数グループ化をキーにして、例をより簡単にしました。

他のヒント

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

これは、linqpadの例の1つから取られています

このようなことをして、物事のリストから数えることができます。

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

単一の要素をカウントします

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

お外側のループがループすべての言葉のリスト。このような原因となります。削除できます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top