我試圖理清這樣的對象列表的機型列表:排序由2個屬性
products.Sort((a, b) =>
{
var x = string.CompareOrdinal(a.SelectToken("model").ToString(), b.SelectToken("model").ToString());
var z = string.CompareOrdinal(b.SelectToken("colour").ToString(), colour);
return x > 0 ? z : x;
});
,然後我通過反向列表要循環,所以我可以刪除重複:
// Loop through products in reverse
for (var i = products.Count() - 1; i >= 0; i--)
{
// Get our product
var product = products[i];
// Get our product colour
var productColour = product.SelectToken("colour").ToString();
// If our colour is black
if (colour == "Black")
{
// If the product colour is not black, remove the duplicate product
if (!productColour.Equals(colour))
products.RemoveAt(i);
}
else
{
// Get our product model
var productModel = product.SelectToken("model").ToString();
// If we are the same model but a different colour, remove the duplicate
if (productModel.Equals(model) && !productColour.Equals(colour))
products.RemoveAt(i);
// Update our variable
model = productModel;
}
}
但它並不僅僅如此簡單。 顏色變量默認爲「黑色」,但可以設置爲任何顏色。所以,我想排序模型第一,然後由顏色,但我想要它,以便它分類顏色這樣。如果顏色是「粉紅」的名單應該是這樣的:
[{
colour: 'Any'
},{
colour: 'Any'
},{
colour: 'Any'
},{
colour: 'Black'
},{
colour: 'Black'
},{
colour: 'Pink'
}]
所以基本上,如果選擇的顏色不是黑色的,它應該是在sort的底部,隨後直接黑(所有其他顏色在這兩個之前)。如果選擇的顏色是黑色,則黑色應該位於列表的底部。 有人可以幫我解決這個問題嗎?
只是爲了信息,這是一個項目的一個例子進行排序:
{
"id": 3797,
"title": "Canon EOS 100D Digital SLR Camera with 18-55 IS STM Lens, HD 1080p, 18MP, 3\" LCD Touch Screen",
"shortTitle": "Canon EOS 100D Black",
"brand": "Canon",
"model": "EOS 100D",
"colour": "Black",
"gtin": "8714574602721",
"image": "http://piiick.blob.core.windows.net/images/Canon-EOS-100D-18-55-Black-8714574602721.png",
"type": "Digital SLR",
"lensFocalLength": "18-55",
"lensType": "IS STM",
"lensMount": "EF/EF-S",
"maxAperture": "999",
"connectivity": "",
"shootingModes": "Scene Intelligent Auto (Stills and Movie), No Flash, Creative Auto, Portrait, Landscape, Close-up, Sports, SCN(Kids, Food, Candlelight, Night Portrait, Handheld Night Scene, HDR Backlight Control), Program AE , Shutter priority AE, Aperture priority AE, Manual (Stills and Movie)",
"weight": 410.0,
"width": 116.8,
"height": 90.7,
"depth": 69.4,
"digitalZoom": "N/A",
"opticalZoom": "N/A",
"waterproof": false,
"maxVideoResolution": "1920 x 1080",
"sensorType": "CMOS",
"sensorSize": "22.3 x 14.9 mm",
"continuousShootingSpeed": "4",
"iso": "1600",
"style": "traditional",
"designer": "",
"dateAnnounced": "10/06/2008",
"focusPoints": 7
}
,一個產品可能不具有黑色的顏色或所選擇的顏色,但我這是完全有可能的不想從我的列表中刪除它(只是重複的模型)。
嘗試用戶'xs.OrderBy(X => ...)。ThenBy(X => ...)'你是做不必要的工作。另外,重複項可以用'xs.GroupBy(x => ...)' –
'OrderBy()。ThenBy()'將不起作用,因爲我需要顏色位於底部,前面是黑色(如果顏色選擇不是黑色)。如果選擇的顏色是黑色的,它會正常工作。此外,'GroupBy'將不起作用,因爲有些模型可能沒有黑色或選定的顏色。 – r3plica
您可以編寫一個自定義鍵比較,將黑色放在開頭。 –