2

リスト内にコードが含まれているすべての結果を取得する LINQ クエリがあります。これは正常に機能しますが、コードのリストに従って順序を維持する必要があります。そのため、EnumerableRowCollection が返されると、行はリストにあったのと同じ順序になります。

これが私の現在のコードです:

if (productcodes != "")
{
    string[] pcodes = productcodes.Split('|');

    // Get most recently viewed first
    Array.Reverse(pcodes);

    List<int> prodCodes = new List<int>();

    foreach (string pc in pcodes)
    {
        if (pc != "")
        {
            prodCodes.Add(Convert.ToInt32(pc));
        }
    }

    results = results.Where(d => d["ProductCode"] != DBNull.Value && (int)d["ID"] > 0 && prodCodes.Contains((int)d["ProductCode"])).Select(d => d);
}

したがって、EnumerableRowCollection の結果は、独自のランダムな順序ではなく、List prodCodes と同じ順序にする必要があります。

何か案は?

4

2 に答える 2

3

必要なのはこれだけです:

IEnumerable<int> pcodes = productcodes.Split('|')
   .Where(s => !string.IsNullOrWhiteSpace(s))
   .Select(s => int.Parse(s))
   .Reverse();

var result = from code in pcodes
             join row in results on code equals row.Field<int>("ProductCode")
             select row;

最後の結合は最初のシーケンス (pcodes) の順序でありProductCodes、「内部結合」で結合されるのは含まれているだけです。

于 2012-10-19T14:13:20.063 に答える
1

Assuming the prodCodes are unique, you can project them into a mapping:

Dictionary<int, int> orderMap = prodCodes
  .Select( (val, i) => new {val, i} )
  .ToDictionary(x => x.val, x => x.i);

Then you can use the orderMap to order the result:

var results = GetSomeResults();
results = results.OrderBy(row => orderMap[(int)row["ProductCode"]]);
于 2012-10-19T14:15:29.607 に答える