【问题标题】:Compare two list based on condition C#根据条件 C# 比较两个列表
【发布时间】:2021-01-28 18:54:01
【问题描述】:

下面是我要实现的点

  1. 通过提供的系统类型(用户输入)获取 TrackId,并记下分期(用户输入 (S,A,E,Q,P))
  2. 按 TrackId && InUse = false 查询 SID 列表
  3. 获取结果并访问属性 Track 例如 0A
  4. 检查是否存在 InUse = true 且具有相同轨道“0A”的任何现有 SID
  5. 如果是 -> 在第 2 步重新开始并添加到条件不是“0A”

这是返回列表的两种方法

var tracklist = _sidRepo.GetTrackSidList(request.systemType);// return point no 2
        var SidList = _sidRepo.GetAllList();// return the whole sid list

现在的问题是我在 tracklist 中有 Sid 对象列表,我想检查 trackId 属性是否存在于第二个列表中,第二个列表的 InUse 属性为真,如果它为真,我不想再次检查它并且添加已经检查 TrackId 的条件,然后从 tracklist 转到下一个 trackid 。有什么想法吗?

【问题讨论】:

  • 我会看看 Set data structure。如果这两个列表包含相同的类型并且没有重复的项目,那么 Set 可能有助于比较。
  • 你能告诉我们SID类的结构吗,第二个列表是什么?也许你可以详细描述,或者结合一个例子来说明。

标签: c# .net linq asp.net-core entity-framework-core


【解决方案1】:

不完全确定你想要什么。但据我了解,你可以试试这个

var tracklist = _sidRepo.GetTrackSidList(request.systemType);// return point no 2
var SidList = _sidRepo.GetAllList();// return the whole sid list
    
// Create a that will track if a trackId has already been checked
var trackIds = new List<int>();
var validTracks = new List<Sid>();

// we create a list of possible ids
var secondListIds = SidList.Select(x => x.TrackId);

// Loop through
foreach(var track in tracklist){

    // Check the exit condition
    if (trackIds.Contains(track.TrackId))
        continue;
        
    // Ok so we havn't seen this track ID before
    // We can check if it the Second list contains it
    if (secondListIds.Contains(track.TrackId))
        // It Does so we add it to the valid Track Ids
        validTracks.add(track);
        
    // Finally add the it to the check list     
    trackIds.Add(track.TrackId);
}

【讨论】:

  • 原则上不要使用List.Contains。请改用Set
  • 或者更确切地说是HashSet
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多