如何过滤列表,使输出中的过滤顺序保持不变。
void Main()
{
var states = new List<State>() { new State("CA", "California"),
new State("NY", "New York"),
new State("AL", "Alabama"),
new State("NV", "Nevada")};
var myOrder = new List<string>() {"AL", "NY"};
var result = states.Where(s => myOrder.Exists(c => string.Equals(c, s.Code, StringComparison.OrdinalIgnoreCase)));
foreach(var res in result)
{
Console.WriteLine(res.Code);
}
//this outputs - NY AL
}
public class State
{
public string Code;
public string Name;
public State(string code, string name)
{
Code = code;
Name = name;
}
}
我需要的输出顺序与myOrder列表中给出的顺序相同(预期输出 - AL NY)。
答案 0 :(得分:3)
如果我正确理解了你想要的东西,那么联接会这样做:
static void Main()
{
//below is a database call, for sake of code simplicity, I have hardcoded few data samples.
var states = new List<State>() {
new State("CA", "California"),
new State("NY", "New York"),
new State("AL", "Alabama"),
new State("NV", "Nevada")
};
var myOrder = new List<string>() { "AL", "DE", "NY", "TX" };
// Join myOrder...
var result = myOrder.Join(
// to states...
states,
// ...on the whole myOrder item...
o => o,
// ...equals the Code field of the State
s => s.Code,
// And the result of the join is just the State
(o, s) => s);
// this outputs - AL NY
foreach (var res in result)
{
Console.WriteLine(res.Code);
}
}
使用myOrder
排序的最简单方法就是从那里开始,不要更改它。有很多方法可以做到这一点,但这样做有用。
答案 1 :(得分:1)
正确地向OrderBy
添加条件:
.OrderBy(s => myOrder.IndexOf(s.Code));
你的情况变成:
var result = states
.Where(s => myOrder.Exists(c => string.Equals(c, s.Code, StringComparison.OrdinalIgnoreCase)))
.OrderBy(s => myOrder.IndexOf(s.Code));