LINQ查询按顺序返回下一个项目

时间:2018-05-17 11:42:52

标签: c# linq

LINQ新手并坚持下去。我有一系列步骤。每个都有一个唯一的ID,一个用于分配各个步骤的ID,以及一个序列(0-7)。我试图传递步骤的唯一ID,但返回分配给下一步的人员的ID。我当前的查询看起来像这样(我知道它错了,只是试图说明:

var nextApproverId = _context.ApprovalSteps
     .Where(p => p.Header.Active == true &&
     p.Sequence == (p.Sequence== (step.sequence + 1))
     .Select(p => p.AssignedApproverId);

步骤看起来像这样

Id      AssignedApproverId      Sequence
123           100                  0
438           101                  1

所以我试图传入Id 123,目的是返回Id 438。

3 个答案:

答案 0 :(得分:2)

var currentId = 123;
var nextApproverId = _context.ApprovalSteps.Single(s => s.sequence == _context.ApprovalSteps.Single(p => p.id == currentId).sequence + 1).Id;
//Returns 438 in your example

创建2个查询:

获得当前序列:

var currentSequence = _context.ApprovalSteps.Single(p => p.id == currentId).sequence;

另一个使用currentSequence来完成下一步:

var nextStep = context.ApprovalSteps.Single(s => s.sequence == _currentSequence + 1);

nextStep.Id为您提供该步骤的ID。

合并:

 var nextApproverId = _context.ApprovalSteps.Single(s => s.sequence == _context.ApprovalSteps.Single(p => p.id == currentId).sequence + 1).Id;

答案 1 :(得分:0)

你的问题在于:

 p.Sequence == (p.Sequence== (step.sequence + 1))

这部分应该是

 var nextApproverId = _context.ApprovalSteps
     .Where(p => p.Header.Active == true &&
     p.Sequence == (step.sequence + 1))
     .Select(p => p.AssignedApproverId);

答案 2 :(得分:0)

以下是可能的答案,请参阅输出here

steps.Select(x =>steps.IndexOf(tags.Where(ele => ele.m_id == id).FirstOrDefault()) + 1).FirstOrDefault();
  

我创建了一个带有我自己的类结构的示例,如OP所描述的具有唯一ID的人类。   要解决这个问题,需要找到当前Id in My case Index of 3 is 1的索引,然后迭代列表,看看当前对象索引是否比用户在In my case the index of output which is "2" is 2 so 2-1 == index of the Id provided as argument by OP提供的索引少1;

class person
{
  public string m_name;
  public int m_id;
  public person(string name,int id)
  {
     m_name = name;
     m_id = id;
  }
}

//主要课程

List<person> steps= new List<person>();
steps.Add(new person("sample",1));
steps.Add(new person("sample1",3));
steps.Add(new person("sample2",2));

int id = 3;
int sample = steps.Where(x => steps.IndexOf(x) - 1 == (steps.IndexOf(steps.Where(ele => ele.m_id == id).FirstOrDefault()))).Select(x => x.m_id).FirstOrDefault();

int sample2 =  steps.Select(x =>steps.IndexOf(steps.Where(ele => ele.m_id == id).FirstOrDefault()) + 1).FirstOrDefault();

// output is 2