我有以下代码:
public List<OversizeElement> GetOversizeRegulations(List<string> states)
{
var tmpList = (from i in _db.States
where states.Any(p=>i.Name == p)
select new
{
StateID = i.ID,
StateName = i.Name,
StateShortName = i.ShortName
}).ToList();
所以,我为“状态”中的所有州选择了其他信息。变量。它有效,但我需要获得相同的顺序,就像在&#39;状态&#39;变量。怎么排序呢?它需要IComparer对象,但我无法想象如何在我的情况下编写它
答案 0 :(得分:2)
如果您想要原始订购,可以执行以下操作:
public List<Destination> GetOversizeRegulations(List<string> states)
{
var tmpDictionary = (from i in _db.States
where states.Contains(i.Name)
select new
{
StateID = i.Id,
StateName = i.Name,
StateShortName = i.ShartName
}
).ToDictionary(k => k.StateName, k => k);
var result = states
.Where(m=>tmpDictionary.ContainsKey(m))
.Select(m => tmpDictionary[m]).ToList();
}
答案 1 :(得分:0)
枚举states
而不是_db.States
:
var tmpList = states
.Select(s => _db.States.SingleOrDefault(st => st.Name == s))
.Where(s => s != null)
.Select(new
{
StateID = s.ID,
StateName = s.Name,
StateShortName = s.ShortName
});
答案 2 :(得分:0)
您可以在IndexOf
功能中使用OrderBy
功能。假设您在两个列表中都有相同的id
字段。让我们在这个例子中说id被称为StateId
:
var tmpList = (from i in _db.States
where states.Any(p=>i.Name == p)
select new
{
StateID = i.ID,
StateName = i.Name,
StateShortName = i.ShortName
}).OrderBy(s => states.Select(x => x.StateId).IndexOf(s.StateId)).ToList();