在linq表达式中创建新对象时,获取列表中的当前索引位置

创建新对象时,我无法从LINQ列表访问当前位置

我尝试声明一个变量并将其在新对象内递增,但没有结果。我没有其他想法。在linq表达式中搜索了一段时间,但找不到答案

-- Sample Data
DeclARE @t TABLE (CustomerName VARCHAR(30))
INSERT  @t VALUES('Johny Smith'),('Freddie Roach'),('Mr. Smithers'),('Johnathan Smithe');

-- User Arguments
DeclARE 
  @name         VARCHAR(30) = 'John Smith',@partialmatch BIT         = 1;

-- Dynamic Solution
SELECT 
  t.CustomerName,Fnmatch = SIGN(pos.F),Lnmatch = SIGN(pos.L)
FROM   @t AS t
CROSS JOIN 
(
  SELECT SUBSTRING(@name,1,f.Mid-1),SUBSTRING(@name,f.Mid+1,8000)
  FROM   (VALUES(CHARINDEX(' ',@name))) AS f(Mid)
) AS f(FName,LName)
CROSS APPLY (VALUES (CHARINDEX(f.FName,t.CustomerName),CHARINDEX(f.LName,t.CustomerName))) AS pos(F,L)
WHERE (@partialmatch = 0 AND pos.F*pos.L > 0)
   OR (@partialmatch = 1 AND pos.F+pos.L > 0);

在“索引位置”中,我需要当前对象的位置。

在此先感谢您的帮助。

gift1226 回答:在linq表达式中创建新对象时,获取列表中的当前索引位置

如果我正确理解了您的问题,则您有List<Document>个对象,并且需要遍历此列表,并为每个步骤的索引创建其他对象。
您返回的值是一个映射(我将在此处使用词典)-Tuple<int,object>

IEnumerable

为什么不简单地使用select这样创建元组:

var mapper = new List<Document>();

var mapping = mapper.
                  Select((doc,n) => new System.Tuple<int,Document>(n,doc)); 

当然select已经可以返回您自己的类型,我假设AddMapping是您自己的扩展方法,但是仍然获得了您的索引文档,您最有可能必须执行以下操作:

var mapper = new List<Document>();

var mapping = mapper.
                  Select((doc,n) => 
                         new System.Tuple<int,Document>(doc.ElementAt(n).Extrato1.Split('.')[0],doc)); 

让我知道这就是您所需要的。

本文链接:https://www.f2er.com/3149301.html

大家都在问