Search code examples
c#jsonlinqindexingjson-deserialization

Write linq query to get records satisfying a condition


I need to write a linq query to get all records from index file for which the (CompRecordPosition == 0 and DPNbr!=0) || (CompRecordPosition!=0).I have written the query as below but the debugger is getting stuck at this line without proceeding further. Please help to get only those index records to _wIndex variable satisfying the given condition

private List<WIndex> _wIndex;
private readonly string _FilePath;
internal const string _Key = "Test";

string idxData = File.ReadAllText(Path.Combine(_FilePath, _Key + ".ind"));
_wIndex = JsonConvert.DeserializeObject<List<WIndex>>(idxData);

_wIndex = _wIndex.Where(p2=>_wIndex
    .Any(p1 => (p2.CompletionRecordPosition == 0  && p2.WbNewestDrlPmtNbr!=0) || 
    p2.CompletionRecordPosition!=0)).ToList();

WIndex Class

public class WIndex
{
    public string BaNo;
    public long RecordPosition;
    public long CompRecordPosition;
    public long SegRecordPosition;
    public string DataType;
    public int RecordIndex;
    public Int32 DpNbr;
}

Index file

  [{
    "BaNo": "7000650000",
    "RecordPosition": 345,
    "CompRecordPosition": 567,
    "SegRecordPosition": 788,
    "DataType": "WELL",
    "RecordIndex": 0,
    "DPNbr": 0
  },
  {
    "BaNo": "7000790001",
    "RecordPosition": 800,
    "CompRecordPosition": 0,
    "SegRecordPosition": 0,
    "DataType": "WELL",
    "RecordIndex": 1,
    "DPNbr": 810
  }]

Solution

  • There's some questions raised in the linq statement you are trying to execute:

    Why use a where then immediately an any clause within the where clause. My recommendation is to eliminate the any clause as its not need to collect items you are requesting from the list.

    Any() - Determines whether an element of a sequence exists or satisfies a condition.

    Where() - Filters a sequence of values based on a predicate.

    Making the statement something like _wIndex.Where(x => x.CompletionRecordPosition == 0 && x.WbNewestDrlPmtNbr != 0).ToList(); would likely be something more preferrable.

    Also, .Any(p1 => ... here p1 is never used or indicated later in any of the lambda expressions. The input parameter can be removed as the relation between p1 and p2 never correlates between the sets. Most likely causing the debug to sit and spin trying to determine what is needed.

    Let me know if this helps - thanks.