LINQ,迭代器,选择和投影 [英] LINQ, iterators, selecting and projection

查看:134
本文介绍了LINQ,迭代器,选择和投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望做的是使用LINQ的风采,同时保持一个迭代器......



基本上

  A类
{
INT位置;
字符串名称;
}

如果我有一个字符串列表,我想他们投射到列表与LT; A> 但该位置在投影填充...

 列表<串GT;名称; //充满串



 列表< A>富=(从s在名称中选择S).ToList(); 



但它也遍历并填充的位置。


$ B ?$ b

这是可能的。

  {{位置:0,名称:名称1},{位置:1 ,产品名称:NAME2},{位置:2,产品名称:NAME3} ....} 


解决方案

您可以这样做:

  VAR listOfStrings =新的List<串> {NAME1,NAME2,NAME3,NAME4}; 
无功富= listOfStrings.Select((价值,位置)=>新建{位置,值})了ToList()。



位置将被增加为0开始的索引,检查的Select方法超载​​。


What I would like to do is use the elegance of LINQ while maintaining an iterator....

essentially

Class A
{
  int Position;
  string Name;
}

if I have a list of strings, i want to project them into List<A> but have the Position be populated in the projection...

List<string> names; //filled with strings

something like

List<A> foo = (from s in names select s).ToList();

but have it also iterate over and populate Position..

is this possible?

{{Position:0,Name: "name1"},{Position:1, Name: "name2"}, {Position:2, Name: "name3"}....}

解决方案

You can do this:

    var listOfStrings = new List<string> {"name1", "name2", "name3", "name4"};
    var foo = listOfStrings.Select((value, position) => new {position, value}).ToList();

Position will be incremented as a 0-starting index, check the Select Method overload.

这篇关于LINQ,迭代器,选择和投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆