我正在尝试填充元组列表,其中元素的数量由可枚举对象确定。 我试图遍历元组列表中的可枚举:
var items = UnitOfWork.GetAll<Table>().Where(x => tableIds.Contains(x.Id));
var tupleList = new List<Tuple<string, string>> {
foreach (var item in items)
{
new Tuple<string, string>(item.A1, item.A2),
new Tuple<string, string>(item.A1, item.A2)
{
};
但这似乎是不允许的(-> 右花括号处的红色摆动线))。 从 Tuple 列表外部循环不会公开 Tuple 列表以供进一步使用。 任何帮助,将不胜感激。问候,马努
根据 Tims 的建议,我的代码现在看起来是这样的:
public IEnumerable<EmailListModel> Get()
{
IIndireKatPrincipal indireKatPrincipal = identityStorage.GetPrincipal();
var groupId = indireKatPrincipal.GroupId;
var araIds = UnitOfWork.GetAll<UserGroup>()
.Where(group => group.Id == groupId)
.SelectMany(group => group.S_ARA).Select(ara => ara.Id);
var aras = UnitOfWork.GetAll<S_ARA>().Where(x => araIds.Contains(x.Id)).AsEnumerable();
List<Tuple<string, string>> tupleList = aras
.Select(ara => new Tuple<string, string>(ara.IEVName, ara.IEVEmail))
.ToList();
var emailListModel = tupleList.Select(entity => new EmailListModel()
{
DisplayAddress = entity.Item1,
EmailAddress = entity.Item2
}).ToList();
return emailListModel;
}
现在它工作完美(在 var aras = ... 添加 .AsEnumerable() 之后)。
最佳答案
您不能在 collection initializer 中使用 foreach
.使用 Select
+ ToList
:
List<Tuple<string, string>> tupleList = items
.Select(item => new Tuple<string, string>(item.A1, item.A2))
.ToList();
Collection initializer: The element initializers can be a simple value, an expression or an object initializer
安expression允许但不是 statement (例如一个循环)
关于c# - 如何填充元素数量由变量确定的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44774690/