本文整理汇总了C#中List.GroupBy方法的典型用法代码示例。如果您正苦于以下问题:C# List.GroupBy方法的具体用法?C# List.GroupBy怎么用?C# List.GroupBy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类List
的用法示例。
在下文中一共展示了List.GroupBy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetDelegateTypes
public static List<ClrType> GetDelegateTypes(ClrDump clrDump)
{
CancellationTokenSource token = new CancellationTokenSource();
clrDump.MessageBus.BeginTask("Analyzing delegate types...", token);
List<ClrType> delegates = new List<ClrType>();
var delegateType = clrDump.GetClrType(typeof(MulticastDelegate).FullName);
foreach(var type in clrDump.AllTypes)
{
clrDump.MessageBus.Status($"Analyzing delegate type: {type.Name}");
if (token.IsCancellationRequested)
{
break;
}
if ( type.BaseType != null && type.BaseType == delegateType )
{
clrDump.MessageBus.Status($"Analyzing delegate type: counting instances for {type.Name}");
int nb = clrDump.CountInstances(type);
if (nb > 0)
{
delegates.Add(type);
}
}
}
clrDump.MessageBus.EndTask("Delegate types analyzed.");
return delegates.GroupBy(t => t.Name).Select(g => g.First()).ToList();
}
示例2: BasicCount_PossiblyRelated
public void BasicCount_PossiblyRelated()
{
var people = new List<Person>
{
new Person{ Firstname="Jim", Lastname="Bob" },
new Person{ Firstname="Joe", Lastname="Bob" },
new Person{ Firstname="Joe", Lastname="John" },
};
Console.WriteLine("Group and count");
var groupedAndCounted = people
.GroupBy(person => person.Lastname)
.Select(grouping => new { Lastname = grouping.Key, Count = grouping.Count() })
.ToList();
Console.WriteLine(string.Join(Environment.NewLine,
groupedAndCounted.Select(personStats => string.Format("Lastname={0}, Count={1}",
personStats.Lastname,
personStats.Count)).ToArray()));
Console.WriteLine("Group and count. Only include items that occur more than once.");
var possibleRelatives = people
.GroupBy(person => person.Lastname)
.Select(grouping => new { Lastname = grouping.Key, Count = grouping.Count() })
.Where(personStats => personStats.Count > 1)
.ToList();
Console.WriteLine(string.Join(Environment.NewLine,
possibleRelatives.Select(personStats => string.Format("Lastname={0}, Count={1}",
personStats.Lastname,
personStats.Count)).ToArray()));
}
示例3: Main
static void Main(string[] args)
{
Console.WriteLine("Interview App");
List<string> names = new List<String> { "dave", "Dave", "DAVE", "ian", "Ian", "IAN", "Ben" };
List<Int32> numbers = new List<Int32> {12, 10, 9, 8, 18, 22, 20,20,12,10,9,8,18};
List<Int32> duplicatenumbers = numbers.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
List<Int32> uniquenumbers = numbers.Distinct().ToList();
List<string> duplicatenames = names.GroupBy(name => name.ToLower()).Where(name => name.Count() > 1).Select(name => name.Key).ToList();
List<string> uniquenames = names.GroupBy(name => name.ToLower()).Where(name => name.Count() == 1).Select(name => name.Key).ToList();
foreach (var name in duplicatenames)
{
Console.WriteLine("Duplicate: " + name);
}
foreach (var name in uniquenames)
{
Console.WriteLine("Unique: " + name);
}
foreach (var number in duplicatenumbers)
{
Console.WriteLine("Duplicate: " + number.ToString());
}
foreach (var number in uniquenumbers)
{
Console.WriteLine("Unique: " + number.ToString());
}
Console.ReadLine();
}
示例4: Main
static void Main()
{
var list = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };
var size = (list.Count / 2) + 1;
var number = list
.GroupBy(g => g)
.Where(s => s.Count() > size)
.Select(x => x.Key);
if (number.Any())
{
Console.WriteLine(string.Join(",", number));
}
else
{
Console.WriteLine("no result");
}
Console.WriteLine(new string('-', 20));
Console.WriteLine("Additional info:");
Console.WriteLine(new string('-', 20));
Console.WriteLine("Size: N/2 + 1 = {0}", size);
var occurances = list.GroupBy(o => o);
foreach (var occurance in occurances)
{
Console.WriteLine("Number[{0}] -> {1} times", occurance.Key, occurance.Count());
}
}
示例5: btnRefresh_Click
private void btnRefresh_Click(object sender, EventArgs e)
{
Clear();
_sqlRecordList = Common.LoadLog<LogEntity>(Common.RunExceptionLogPathKey);
_sqlRecordList = _sqlRecordList.OrderByDescending(o => o.CreateAt.ToString("yy-MM-dd HH:mm")).ToList();
foreach (var result in _sqlRecordList.GroupBy(o => o.CreateAt.ToString("yy-MM-dd"))) { if (result.Key != null) { coxDate.Items.Add(result.Key); } }
foreach (var result in _sqlRecordList.GroupBy(o => o.MethodName)) { if (result.Key != null) { coxMethodName.Items.Add(result.Key); } }
btnSelect.PerformClick();
}
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
list = Medlem.GetMedlemmer();
rptDepartments.DataSource = list.GroupBy(x => x.Årgang).OrderBy(x => x.Key).Select(x => new { Afdeling = x.Key }).ToList();
if( !IsPostBack )
dd.Items.AddRange(list.GroupBy(x => x.Årgang).OrderBy(x => x.Key).Select(x => new ListItem { Text = x.Key }).ToArray());
if( Request.QueryString["afdeling"] != null )
memberList.DataSource = list.Where(x => x.Årgang.StartsWith(Afdeling));
DataBind();
}
示例7: Update
public void Update(RealTimeData s)
{
List<BuyOrder> buylist = new List<BuyOrder>();
int i = 0;
foreach (BuyOrder value in comp.Buyorder)
{
if (i < 10)
buylist.Add(value);
i++;
}
realdata = s;
dataGridView1.Rows.Clear();
IEnumerable<IGrouping<float, BuyOrder>> collection = buylist.GroupBy(b => b.orderPrice).OrderBy(b => b.Key).Reverse();
foreach (IGrouping<float, BuyOrder> orders in collection)
{
int vol = 0;
//go through each buyorder
foreach (BuyOrder buyo in orders)
{
vol += buyo.orderSize;
//pocket full of mumbles
dataGridView1.Rows.Add(orders.Count(), vol, orders.Key);//orders.count() is how many times that order was made
}
}
IEnumerable<IGrouping<float, BuyOrder>> collection2 = buylist.GroupBy(b => b.orderPrice).OrderBy(b => b.Key).Reverse();
dataGridView2.Rows.Clear();
foreach (IGrouping<float, BuyOrder> orders2 in collection2)
{
int vol = 0;
//go through each buyorder
foreach (BuyOrder buyo in orders2)
{
vol += buyo.orderSize;
//pocket full of mumbles
dataGridView2.Rows.Add(orders2.Count(),vol, orders2.Key);//orders.count() is how many times that order was made
}
}
}
示例8: Main
public static void Main()
{
List<Student> students = new List<Student>();
Student ivan = new Student("Ivan", "Ivanov", "141000", "02325123", "[email protected]", 1);
students.Add(ivan);
Student gosho = new Student("Gosho", "Goshev", "141001", "052222222", "[email protected]", 1);
students.Add(gosho);
Student pesho = new Student("Pesho", "Mastikata", "141002", "052123634", "[email protected]", 2);
students.Add(pesho);
Student kiro = new Student("Kiro", "Leshnikov", "141003", "03225123", "[email protected]", 2);
students.Add(kiro);
Student maria = new Student("Maria", "Dimitrova", "141004", "056251231", "[email protected]", 3);
students.Add(maria);
Student vanq = new Student("Vanq", "Ivanova", "141005", "032412413", "[email protected]", 2);
students.Add(vanq);
var groups = students.GroupBy(student => student.GroupNumber);
//foreach (var group in groups)
//{
// Console.WriteLine("Group: " + group.Key);
// foreach (var name in group)
// {
// Console.WriteLine("\t{0} {1}", name.FirstName, name.LastName);
// }
//}
var orderedGroups = students.OrderByGroup();
foreach (var orderedItems in orderedGroups)
{
Console.WriteLine("Group: " + orderedGroups);
Console.WriteLine("\t{0} {1}", orderedItems.FirstName, orderedItems.LastName);
}
}
示例9: RemoveExistingPatients
public List<IPatient> RemoveExistingPatients(List<IPatient> patients)
{
foreach (var patientGroup in patients.GroupBy(p => p.GetCPF()).GroupBy(e => e.Key))
{
foreach (var patientValue in patientGroup)
{
IPatient patientUnique = new Patient();
foreach (var patient in patientValue)
{
if (string.IsNullOrEmpty(patientUnique.Id))
{
patientUnique = patient;
patient.AddRecord(new Record() { Code = patient.Id, Hospital = patient.Hospital });
PatientsDb.Add(patient);
}
else
{
if (patientUnique.Records != null)
{
var record = patientUnique.Records.Find(r => r.Code == patient.Id);
if (record != null)
continue;
}
patientUnique.AddRecord(new Record() { Code = patient.Id, Hospital = patient.Hospital });
}
}
}
}
return PatientsDb;
}
示例10: Main
static void Main(string[] args)
{
int[] arr = new int[5];
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine("Enter a number");
arr[i] = int.Parse(Console.ReadLine());
}
List<int> red = new List<int>(arr);
var group = red.GroupBy(i => i);
foreach (var item in group)
{
List<int> red2 = new List<int>();
Console.WriteLine("The number {0} occurs {1} times", item.Key, item.Count());
if(item.Count()%2!=0)
{
red2.Add(red[item.Count()]);
}
foreach (var gs in red2)
{
Console.WriteLine(gs);
}
}
}
示例11: GetBindings
/// <summary>
/// Gets the presenter bindings for passed views using the passed hosts.
/// </summary>
/// <param name="hosts">A list of view hosts (master pages, pages, etc).</param>
/// <param name="viewInstances">A list of view instances (user controls, pages, etc).</param>
public IEnumerable<PresenterDiscoveryResult> GetBindings(IEnumerable<object> hosts, IEnumerable<IView> viewInstances)
{
var results = new List<PresenterDiscoveryResult>();
var pendingViewInstances = viewInstances;
foreach (var strategy in strategies)
{
if (!pendingViewInstances.Any())
break;
var resultsThisRound = strategy.GetBindings(hosts, pendingViewInstances);
results.AddRange(resultsThisRound);
var viewsBoundThisRound = resultsThisRound
.Where(r => r.Bindings.Any())
.SelectMany(b => b.ViewInstances)
.Distinct();
pendingViewInstances = pendingViewInstances
.Except(viewsBoundThisRound);
}
return results
.GroupBy(r => r.ViewInstances, viewInstanceListComparer)
.Select(r => BuildMergedResult(r.Key, r));
}
示例12: Main
//Write a program to find the longest area of equal elements in array of strings.You first should read an integer n and n strings(each at a separate line), then find and print the longest sequence of equal elements(first its length, then its elements). If multiple sequences have the same maximal length, print the leftmost of them.
static void Main()
{
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
List<string> strings = new List<string>();
for (int i = 0; i < n; i++)
{
strings.Add(Console.ReadLine());
}
var result = strings.GroupBy(x => x).Select(x => new
{
Name = x.Key,
Total = x.Count()
});
int biggestCount = 0;
string longestArea = "";
foreach (var s in result)
{
if (s.Total > biggestCount)
{
biggestCount = s.Total;
longestArea = s.Name;
}
}
Console.WriteLine(biggestCount);
for (int i = 0; i < biggestCount; i++)
{
Console.WriteLine(longestArea);
}
}
示例13: NaiveBayes
public NaiveBayes(List<Case> cases)
{
this.classProbabilities = new List<ClassGrouping>();
this.attrProbabilities = new List<AttrGroupings>();
for (int i = 0; i < cases.First().attributes.Count; i++)
attrProbabilities.Add(new AttrGroupings(cases, i));
var originalGroupings = cases.GroupBy(c => c.classification).ToList();
if (originalGroupings.Count <= 25)
{
for (int i = 0; i < originalGroupings.Count; i++)
{
double probability = (double)originalGroupings[i].Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1.
this.classProbabilities.Add(new ClassGrouping(originalGroupings[i].ToList(), this.attrProbabilities, probability));
}
}
else
{
List<Case> temp = cases.OrderBy(c => c.classification).ToList();
int takeCount = temp.Count / numOfGroupings;
for (int i = 0; i < numOfGroupings; i++)
{
List<Case> temp2;
if (i != numOfGroupings - 1) temp2 = temp.Skip(takeCount * i).Take(takeCount).ToList();
else temp2 = temp.Skip(takeCount * i).ToList();
double probability = (double)temp2.Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1.
this.classProbabilities.Add(new ClassGrouping(temp2, this.attrProbabilities, probability));
}
}
}
示例14: Generate_Duplicated_ItemList
private static void Generate_Duplicated_ItemList(List<FileStruct> t, string output_filename)
{
try
{
List<FileStruct> duplicateItems = t
.GroupBy(x => x.hash)
.Where(x => x.Count() > 1)
.SelectMany(x => x).ToList();
if (duplicateItems.Any())
{
StringBuilder builder = new StringBuilder();
using (FileStream file = File.Create(output_filename))
{ }
foreach (var fss in duplicateItems)
{
builder.Append(fss.hash + " *" + fss.Name).AppendLine();
}
if (builder.Length > 0)
{
using (TextWriter writer = File.CreateText(output_filename))
{
writer.Write(builder.ToString());
}
builder.Clear();
}
}
}
catch (Exception)
{
throw;
}
}
示例15: Main
private static void Main()
{
var numberSequence = new List<int> { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 };
var countDictionary = numberSequence.GroupBy(number => number)
.ToDictionary(group => group.Key, group => group.Count());
Console.WriteLine(string.Join(", ", numberSequence.Where(number => countDictionary[number] % 2 == 0)));
}