我有一个Linq查询,我将传递给一个列表,然后通过viewbag传递给视图。我试图按照特定的顺序保留该列表,这样当我遍历它时,我可以控制它显示的顺序。
以下是查询:
from flask import Flask, render_template, redirect, request
from xml_identifiersearch import searchXML, printHTML
from xml_time import sortDate, returnDateFile, dateRange, searchXML, printDateHTML
app = Flask(__name__)
@app.route('/')
def index():
return render_template('home.html')
@app.route('/',methods=['POST'])
def run():
printHTML(request.form['input'])
return render_template('home.html')
@app.route('/',methods=['POST'])
def run2():
startYear=request.form['startYear']
startMonth=request.form['startMonth']
startDay=request.form['startDay']
startHour=request.form['startHour']
startMinute=request.form['startMinute']
startSecond=request.form['startSecond']
startMillisecond=request.form['startMillisecond']
endYear=request.form['endYear']
endMonth=request.form['endMonth']
endDay=request.form['endDay']
endHour=request.form['endHour']
endMinute=request.form['endMinute']
endSecond=request.form['endSecond']
endMillisecond=request.form['endMillisecond']
startDatetime=startYear+"-"+startMonth+"-"+startDay+"T"+startHour+":"+startMinute+":"+startSecond+"."+startMillisecond+"Z"
endDatetime=endYear+"-"+endMonth+"-"+endDay+"T"+endHour+":"+endMinute+":"+endSecond+"."+endMillisecond+"Z"
printDateHTML(startDatetime, endDatetime)
return render_template('home.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000,debug=True)
我成功地将此列表传递给视图并迭代它,但无论值始终按字母顺序显示。 ViewBag.attributes = (From row In db.tblCategory_Attributes
Where row.Item_Type_Identifier = itemType
Order By row.Category_Attribute_Identifier
Select CStr(row.Attribute_Name)
Distinct).ToList()
是一个整数,与我希望显示这些值的顺序一致。
我已经玩了很多我的陈述的顺序,我没有运气。
您能告诉我如何明确选择与我的特定Category_Attribute_Identifier
相关的Attribute_Name
并按Item_Type_Identifier
订购我的结果吗?
答案 0 :(得分:1)
Distinct
再次创建自己的排序(因为它会对结果进行混洗以过滤掉重复项)。只需在Distinct
:
(From row In db.tblCategory_Attributes
Where row.Item_Type_Identifier = itemType
Select row
Distinct)
.OrderBy(Function(row) row.Category_Attribute_Identifier)
.Select(Function(row) CStr(row.Attribute_Name))
答案 1 :(得分:1)
尝试使用Group By
代替Distinct
ViewBag.attributes = (From row In db.tblCategory_Attributes _
Where row.Item_Type_Identifier = itemType _
Order By row.Category_Attribute_Identifier) _
.AsEnumerable() _
.GroupBy(Function(r) r.Attribute_Name) _
.Select(Function(g) g.Key) _
.ToList()
或者使用扩展方法语法,它允许您以任何顺序自由地应用扩展方法:
ViewBag.attributes = db.tblCategory_Attributes _
.Where(Function(row) row.Item_Type_Identifier = itemType) _
.Select(Function(row) New With {row.Attribute_Name, row.Category_Attribute_Identifier}) _
.Distinct() _
.OrderBy(Function(a) a.Category_Attribute_Identifier) _
.Select(Function(a) a.Attribute_Name) _
.ToList()
这个简单的测试表明GroupBy
保留了顺序:
Public Shared Sub TestGroupOrder()
Dim a = New Integer() {6, 2, 4, 2, 7, 5, 3, 4}
Dim query = a.GroupBy(Function(i) i).[Select](Function(g) g.Key)
For Each i As Integer In query
Console.Write("{0} ", i)
Next
End Sub
控制台中的结果:
6 2 4 7 5 3