我如何迭代Linq组结果集
本文关键字:Linq 结果 迭代 何迭代 | 更新日期: 2023-09-27 18:01:29
我从数据库中获得一些数据,并使用linq计算总和和计数并对数据进行分组。这是我的文件:
var si = _repository.GetAllByDate(date);
var cs = from s in si
group s by s.Name into g
select new { Comm = g.Key, SIList = g.ToList(), Count = g.Count() };
我现在需要将cs传递给另一个类中的方法,以便我可以提取Comm, SIList和Count为组中的每个项目,我传递它作为什么类型?IEnumerable不起作用。实际的linq组结果类型似乎是:
{System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<Model.Domain.MasterData
.MyItem,Model.Domain.SI<>f__AnonymousTyped<Model.Domain.MasterData.MyItem,System.Collections.Generic.List<Model.Domain.SI>,int>>}
任何想法?我想有效地传递cs作为一个变量并在那里迭代它
如果要在不同范围内使用匿名类型,则需要创建一个与匿名类型定义匹配的类型。
public class SomeClass {
public Comm Comm { get; set; }
public IList<String> SIList { get; set; }
public Int32 Count { get; set; }
}
var si = _repository.GetAllByDate(date);
var cs = from s in si
group s by s.Name into g
select new SomeClass { Comm = g.Key, SIList = g.ToList(), Count = g.Count() };
EDIT:我想我们可以假设列表将是String
,所以我正在为此编辑。如果这是错误的类型,你需要改变相应的IList<T>
定义
得到如此复杂类型的原因是查询使用延迟执行。您正在查看返回结果的表达式的类型,而不是结果的类型。
结果的类型是IEnumerable<_hidden_internal_class_name_>
,即当您在查询中创建匿名对象时,结果是编译器在内部创建的类的对象流。
将结果传递给另一个方法是非常无用的,因为它需要使用反射来读取对象中的属性。您应该为结果中的对象创建一个命名类,以便于访问其属性。
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
// Uses method-based query syntax.
public static void GroupByEx1()
{
// Create a list of pets.
List<Pet> pets =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 },
new Pet { Name="Daisy", Age=4 } };
// Group the pets using Age as the key value
// and selecting only the pet's Name for each value.
IEnumerable<IGrouping<int, string>> query =
pets.GroupBy(pet => pet.Age, pet => pet.Name);
// Iterate over each IGrouping in the collection.
foreach (IGrouping<int, string> petGroup in query)
{
// Print the key value of the IGrouping.
Console.WriteLine(petGroup.Key);
// Iterate over each value in the
// IGrouping and print the value.
foreach (string name in petGroup)
Console.WriteLine(" {0}", name);
}
}
/*
This code produces the following output:
8
Barley
4
Boots
Daisy
1
Whiskers
*/
创建类型是一个很好的想法,但是当返回的Tuple可以在不创建新类或结构的情况下完成时,为什么要这样做?如果需要是本地的或内部的,并且类不会被重用,请尝试使用Tuple。
Select new Tuple<Comm, IEnumerable<string>, Int32>( new Comm(), myStringList.AsEnumerable(), myCount )
将其作为object
传递,并在foreach
循环中使用var
作为迭代器。