本文整理汇总了C#中ObservableCollection.OrderByDescending方法的典型用法代码示例。如果您正苦于以下问题:C# ObservableCollection.OrderByDescending方法的具体用法?C# ObservableCollection.OrderByDescending怎么用?C# ObservableCollection.OrderByDescending使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ObservableCollection
的用法示例。
在下文中一共展示了ObservableCollection.OrderByDescending方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CommentRequestCommentsByLandReceived
private void CommentRequestCommentsByLandReceived(object sender, EventArgs e)
{
comments = new ObservableCollection<Comment>(sender as List<Comment>);
comments.CollectionChanged += comments_CollectionChanged;
if (comments != null)
{
NumberOfCommentsText.Text = comments.Count.ToString();
commentList.ItemsSource = comments.OrderByDescending(x => x.Published).Take(2);
}
}
示例2: LoadData
public async Task<WiFiScanResultTypes> LoadData() {
Enabled_btnRefresh = false;
ShowRunning();
WifiNetworks = new ObservableCollection<WiFiAvailableNetwork>();
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed) {
Enabled_btnRefresh = true;
HideRunning();
return WiFiScanResultTypes.NO_ACCESS_TO_WIFI_CARD;
}
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
if (result.Count > 0) {
PrimaryAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
} else {
Enabled_btnRefresh = true;
HideRunning();
return WiFiScanResultTypes.NO_WIFI_CARD;
}
await PrimaryAdapter.ScanAsync();
foreach (var network in PrimaryAdapter.NetworkReport.AvailableNetworks) {
WifiNetworks.Add(network);
}
WifiNetworks = new ObservableCollection<WiFiAvailableNetwork>(WifiNetworks.OrderByDescending(a => a.SignalBars));
Enabled_btnRefresh = true;
HideRunning();
return WiFiScanResultTypes.SUCCESS;
}
示例3: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
XmlNodeList _names = null, _scores = null;
bool fileExists = true;
try
{
StorageFile st = await ApplicationData.Current.LocalFolder.GetFileAsync("score.xml");
dom = await XmlDocument.LoadFromFileAsync(st);
_names = dom.GetElementsByTagName("name");
_scores = dom.GetElementsByTagName("highscore");
}
catch (Exception)
{
fileExists = false;
}
playerTable = new ObservableCollection<Player>();
if (fileExists)
{
for (int i = 0; i < _names.Count; i++)
{
string name = _names.ElementAt(i).InnerText;
int score = Int32.Parse(_scores.ElementAt(i).InnerText);
playerTable.Add(new Player(name, score));
}
}
playerTable = new ObservableCollection<Player>(playerTable.OrderByDescending(player => player.Score));
playerTable = new ObservableCollection<Player>(playerTable.Take(10));
foreach (var elem in playerTable)
{
LeaderBoardControl control = new LeaderBoardControl(elem.Name, elem.Score);
leaderBoardList.Items.Add(control);
}
}
示例4: SetFromFile
public void SetFromFile(string fileName)
{
Categories.Clear();
ObservableCollection<CategoryViewModel> tempList = new ObservableCollection<CategoryViewModel>();
using (ZipFile zip = ZipFile.Read(fileName))
{
foreach(var entry in zip.OrderByDescending(item=>item.CompressedSize))
{
string category = GetCategoryForFile(entry.FileName);
var categoryVm = GetOrCreateCategoryFor(category, tempList);
FileViewModel fileVm = new FileViewModel();
fileVm.Name = entry.FileName;
fileVm.SizeInBytes = entry.CompressedSize;
categoryVm.Files.Add(fileVm);
}
}
foreach (var category in tempList)
{
category.RecalculateEverything();
}
var totalSize = tempList.Sum(item => item.SizeInBytes);
foreach (var category in tempList)
{
category.ContainingZipSize = totalSize;
}
foreach(var category in tempList.OrderByDescending(item=>item.SizeInBytes))
{
Categories.Add(category);
}
}
示例5: Items_Are_Ordered_According_To_Orderer_When_Added_After_Mirror_Call
public void Items_Are_Ordered_According_To_Orderer_When_Added_After_Mirror_Call()
{
var target = new List<int>();
var source = new ObservableCollection<int> { 1, 2, 3, 4, 5 };
// This will sort the items descending
target.Mirror(source, x => x, orderer: (x, y) => Comparer<int>.Default.Compare(x, y) * -1);
source.Add(0);
source.Add(-1);
target.Should().Equal(source.OrderByDescending(x => x));
}
示例6: SelectedCustomer_Changed
private void SelectedCustomer_Changed(object sender, SelectionChangedEventArgs e)
{
if (this.SelectedCustomer == null) { return; }
var charges = new ObservableCollection<Charge>();
foreach (WorkDay day in this._DB.WorkDay.Where(o => (this.ShowAllCharges ? true : o.Printed == null) && o.CustomerID == this.SelectedCustomer.CustomerID))
{
charges.Add(new Charge(day));
}
foreach (MiscCharge misc in this._DB.MiscCharge.Where(o => (this.ShowAllCharges ? true : o.Printed == null) && o.CustomerID == this.SelectedCustomer.CustomerID))
{
charges.Add(new Charge(misc));
}
this.Charges = new ObservableCollection<Charge>(charges.OrderByDescending(o => o.Date));
}
示例7: Load
public void Load()
{
var databaseFile = new FileInfo(_databasePath);
if (!databaseFile.Exists)
{
SQLiteConnection.CreateFile(databaseFile.FullName);
_connection = new SQLiteConnection($"Data Source={databaseFile.FullName};Version=3;");
_connection.Open();
//_connection.ChangePassword(Password);
using (
var command =
new SQLiteCommand(
"CREATE TABLE `PlayTimes` (Timestamp DATETIME NOT NULL, Duration VARCHAR(50), Program VARCHAR(36), Guid VARCHAR(36) NOT NULL, PRIMARY KEY (Guid))",
_connection))
command.ExecuteNonQuery();
using (
var command =
new SQLiteCommand(
"CREATE TABLE `Programs` (Timestamp DATETIME NOT NULL, Path VARCHAR(50), IsGame INT, Name VARCHAR(512), Guid VARCHAR(36) NOT NULL, PRIMARY KEY (Guid))",
_connection))
command.ExecuteNonQuery();
}
else
{
_connection = new SQLiteConnection($"Data Source={databaseFile.FullName};Version=3;"); //Password={Password};
_connection.Open();
}
PlayTimes = new ObservableCollection<PlayTime>();
using (var command = new SQLiteCommand("SELECT * FROM `PlayTimes`", _connection))
{
var reader = command.ExecuteReader();
while (reader.Read())
{
PlayTimes.Add(new PlayTime
{
Timestamp = reader.GetDateTime(0),
Duration = XmlConvert.ToTimeSpan(reader[1].ToString()),
Program = Guid.ParseExact(reader[2].ToString(), "D"),
Guid = Guid.ParseExact(reader[3].ToString(), "D")
});
}
}
Programs = new ObservableCollection<Program>();
using (var command = new SQLiteCommand("SELECT * FROM `Programs`", _connection))
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Programs.Add(new Program
{
Timestamp = reader.GetDateTime(0),
Path = reader[1].ToString(),
IsGame = reader.GetInt32(2) == 1,
Name = reader[3]?.ToString(),
Guid = Guid.ParseExact(reader[4].ToString(), "D")
});
}
}
var time = PlayTimes.OrderByDescending(x => x.Timestamp).FirstOrDefault();
if (time?.Duration == TimeSpan.Zero)
{
var lastShutdownTime = GetLastSystemShutdown();
if (time.Timestamp < lastShutdownTime) //Else we would go negative
{
PlayTimeFinished(time, lastShutdownTime);
}
else
{
using (var command = new SQLiteCommand($"DELETE FROM `PlayTimes` WHERE Guid='{time.Guid.ToString("D")}'", _connection)) //We delete the entry, there was an error
command.ExecuteNonQuery();
PlayTimes.Remove(time);
}
}
}
示例8: InitCategories
private ObservableCollection<CategoryWithBar> InitCategories()
{
var allCategories = _transactionsService.GetAll()
.Where(x => x.ReportingPeriod.MoneyBoxId == MoneyBox.Id)
.Select(s => new { s.Category.Image, s.Category.Title, s.Category.Type, s.ReportingPeriod })
.Distinct()
.ToList();
if (MonthVisible)
allCategories = allCategories
.Where(x => x.ReportingPeriod.Period.Month == Period.Month &&
x.ReportingPeriod.Period.Year == Period.Year)
.ToList();
else
allCategories = allCategories
.Where(x => x.ReportingPeriod.Period.Year == Period.Year)
.ToList();
switch (FilterOption)
{
case "Incomes":
allCategories = allCategories.Where(x => x.Type == TransactionType.Income).ToList();
break;
case "Expences":
allCategories = allCategories.Where(x => x.Type == TransactionType.Expence).ToList();
break;
}
var filteredCategories = new ObservableCollection<CategoryWithBar>(
allCategories.Select(x => new CategoryWithBar()
{
Image = x.Image,
CurrencySymbol = MoneyBox.CurrencySymbol,
Title = x.Title,
Type = x.Type,
Value = _transactionsService.GetAll()
.Where(c => c.ReportingPeriod.MoneyBoxId == MoneyBox.Id && c.Category.Title.Equals(x.Title) && c.Category.Type == x.Type)
.Sum(s => s.Value * s.ToPrimaryCoeff),
Total = x.Type == TransactionType.Income ?
_reportingPeriodService.GetIncomeForSpecPeriod(MoneyBox.Id, Period, MonthVisible) :
_reportingPeriodService.GetExpenceForSpecPeriod(MoneyBox.Id, Period, MonthVisible)
}));
switch (SortOption)
{
case "Ascending":
return new ObservableCollection<CategoryWithBar>(filteredCategories.OrderBy(o => o.Value));
case "Descending":
return new ObservableCollection<CategoryWithBar>(filteredCategories.OrderByDescending(o => o.Value));
default:
return new ObservableCollection<CategoryWithBar>(filteredCategories.OrderByDescending(o => o.Value));
}
}
示例9: Refresh
private void Refresh()
{
dtGrid.ItemsSource = null;
_messageList = new ObservableCollection<Message>(App.am.Messages);
dtGrid.ItemsSource = _messageList.OrderByDescending(k => k.Id);
CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(dtGrid.ItemsSource);
view.Filter = UserFilter;
port.Text = "ALL";
port.Text = port.Text + Environment.NewLine + "Message No.: " + _messageList.Count().ToString();
port.Text = port.Text + Environment.NewLine + "Unsent : " + _messageList.Where(k => k.Sent == "F").Select(t => t.Sent).Count().ToString();
port.Text = port.Text + Environment.NewLine + "Sent : " + _messageList.Where(k => k.Sent == "T").Select(t => t.Sent).Count().ToString();
portToday.Text = "TODAY";
portToday.Text = portToday.Text + Environment.NewLine + "Message No.: " + _messageList.Where(k => Convert.ToDateTime(k.Dor).Date.ToString("d") == DateTime.Now.ToString("d")).Count().ToString();
portToday.Text = portToday.Text + Environment.NewLine + "Unsent : " + _messageList.Where(k => k.Sent == "F" && Convert.ToDateTime(k.Dor).Date.ToString("d") == DateTime.Now.ToString("d")).Select(t => t.Sent).Count().ToString();
portToday.Text = portToday.Text + Environment.NewLine + "Sent : " + _messageList.Where(k => k.Sent == "T" && Convert.ToDateTime(k.Dor).Date.ToString("d") == DateTime.Now.ToString("d")).Select(t => t.Sent).Count().ToString();
}
示例10: SortIssues
/// <summary>
/// Sorts the issues.
/// </summary>
/// <param name="issues">The issues.</param>
private void SortIssues(ObservableCollection<IssueViewModel> issues)
{
List<IssueViewModel> list = issues.OrderByDescending(i => i.Model.CreationDate).ToList();
for (int i = 0; i < issues.Count; i++)
{
issues[i] = list[i];
}
}
示例11: ReadContactList_Loaded
//READ db list
private void ReadContactList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbcontacts = new ReadAllContactsList();
DB_ContactList = dbcontacts.GetAllContacts();//Vai buscar os contactos
if (DB_ContactList.Count > 0)
{
}
lista.ItemsSource = DB_ContactList.OrderByDescending(i => i.Model.C_nome).ToList();//
}
示例12: SearchBooks
//.........这里部分代码省略.........
ns.AddNamespace("atom", "http://www.w3.org/2005/Atom");
ns.AddNamespace("dc", "http://purl.org/dc/terms");
var xelRoot = xdcDocument.DocumentElement;
var xnlNodes = xelRoot.SelectNodes("//atom:entry", ns);
foreach (XmlNode xndNode in xnlNodes)
{
var searchResult = new SearchResult();
var book = new Book();
var xmlTitle = xndNode["title"];
if (xmlTitle != null)
{
book.Title = xmlTitle.InnerText;
}
var xmlDatePublished = xndNode["dc:date"];
if (xmlDatePublished != null)
{
var dp = xmlDatePublished.InnerText;
if (dp.Length == 4)
{
var dt = Convert.ToDateTime(string.Format("01/01/,{0}", dp));
book.DatePublished = dt;
}
else
{
DateTime dt;
if (DateTime.TryParse(dp, out dt))
{
book.DatePublished = dt;
}
}
}
var xmlDescription = xndNode["dc:description"];
if (xmlDescription != null)
{
// Remove ASCII Control Characters
book.Abstract = xmlDescription.InnerText.Replace("'", "'");
book.Abstract = xmlDescription.InnerText.Replace(""", string.Empty);
}
var formatNodes = xndNode.SelectNodes("dc:format", ns);
if (formatNodes != null)
{
foreach (XmlNode node in formatNodes)
{
if (node.InnerText.Contains("pages"))
{
var resultString = Regex.Match(node.InnerText, @"\d+").Value;
book.Pages = Convert.ToInt32(resultString);
}
}
}
var identifierNodes = xndNode.SelectNodes("dc:identifier", ns);
if (identifierNodes != null)
{
foreach (XmlNode node in identifierNodes)
{
if (node.InnerText.Length == 18) // 13 digit ISBN Node
{
book.Isbn = Regex.Match(node.InnerText, @"\d+").Value;
}
}
}
var xmlPublisher = xndNode["dc:publisher"];
if (xmlPublisher != null)
{
searchResult.Publishers.Add(new Publisher {Name = xmlPublisher.InnerText});
}
var xmlAuthor = xndNode["dc:creator"];
if (xmlAuthor != null)
{
var words = xmlAuthor.InnerText.Split(' ');
if (words.Length == 1)
{
searchResult.Authors.Add(new Author {LastName = words[0]});
}
else
{
searchResult.Authors.Add(new Author
{
FirstName = words[0],
LastName = words[1]
});
}
}
book.Scraped = true;
searchResult.Book = book;
// searchResult.Percentage = MatchStrings.Compute(searchQuery.ToString(), book.Title)*100;
searchResults.Add(searchResult);
}
var s = searchResults.OrderByDescending(x => x.Percentage);
return new ObservableCollection<SearchResult>(s);
}
示例13: LoadAll
public async Task<ObservableCollection<News>> LoadAll()
{
ObservableCollection<News> NewsList = new ObservableCollection<News>();
News tempNews = new News();
int i = 0;
while ((tempNews = await _factory.Read<News>("News-" + i + ".xml")) != null)
{
NewsList.Add(tempNews);
i++;
}
return new ObservableCollection<News>(NewsList.OrderByDescending(x => x.PublishDate));
}
示例14: GetDataFromWeb
async private void GetDataFromWeb()
{
progressbar.Text = "Fetching new data";
progressbar.ShowAsync();
var client = new HttpClient();
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (!localSettings.Containers.ContainsKey("userInfo"))
{
MessageDialog msgbox = new MessageDialog("Please log-in first. Go to settings from the main menu.");
await msgbox.ShowAsync();
return;
}
var lastcheck = localSettings.Containers["userInfo"].Values["lastchecktips"].ToString();
Debug.WriteLine(System.Uri.EscapeUriString(lastcheck));
var response = await client.GetAsync(new Uri("http://codeinn-acecoders.rhcloud.com:8000/query/data?Timestamp=" + System.Uri.EscapeUriString(lastcheck) + "&Table=Tips"));
var result = await response.Content.ReadAsStringAsync();
result = result.Trim(new Char[] { '"' });
Debug.WriteLine(result);
DatabaseTip Db_Helper = new DatabaseTip();
try
{
List<Tips> newprobs = JsonConvert.DeserializeObject<List<Tips>>(result);
foreach (Tips prob in newprobs)
{
try
{
Db_Helper.InsertTip(prob);
}
catch
{
Debug.WriteLine("DB error for item of id: " + prob.Id);
}
}
localSettings.Containers["userInfo"].Values["lastchecktips"] = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
progressbar.Text = "New items";
}
catch
{
Debug.WriteLine("No new items");
progressbar.Text = "No New items";
}
finally
{
ReadTips dbtips = new ReadTips();
DB_TipList = dbtips.GetAllTips();
listBox.ItemsSource = DB_TipList.OrderByDescending(i => i.Id).ToList();
}
progressbar.HideAsync();
}
示例15: TopFeed
/// <summary>
/// Returns a list of top tracks
/// </summary>
/// <returns>An observable collection of TrackData that represents the top SoundCloud tracks</returns>
public static ObservableCollection<TrackData> TopFeed()
{
ObservableCollection<TrackData> tracks = new ObservableCollection<TrackData>();
try
{
// soundcloud removed order=hotness and seemingly any order.
// so instead we fetch the unofficial explore feed and do a second
// request to resolve IDs to track structures.
try
{
var url = "https://api-v2.soundcloud.com/explore/Popular%2BMusic?limit=50&offset=0&linked_partitioning=1";
var request = (HttpWebRequest)WebRequest.Create(url);
var unsortedTracks = new ObservableCollection<TrackData>();
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
// fetch a list of IDs for all tracks in explore categories
JObject exploreFeed = JObject.Parse(reader.ReadToEnd());
JArray exploreCollection = exploreFeed["tracks"] as JArray;
List<string> trackIDs = new List<string>();
foreach (JObject track in exploreCollection)
{
try
{
trackIDs.Add(track["id"].ToString());
}
catch { }
}
// turn IDs into track structures
if (trackIDs.Count > 0)
{
int offset = 0;
while (true)
{
url = CreateURL("tracks", new string[] { "ids=" + String.Join(",", trackIDs), String.Format("offset={0}", offset), "limit=50" });
request = (HttpWebRequest)WebRequest.Create(url);
using (var tracksResponse = (HttpWebResponse)request.GetResponse())
{
using (var tracksReader = new StreamReader(tracksResponse.GetResponseStream()))
{
try
{
ObservableCollection<TrackData> nextTracks = ParseTracks(JArray.Parse(tracksReader.ReadToEnd()));
if (nextTracks.Count == 0)
break;
foreach (TrackData t in nextTracks)
unsortedTracks.Add(t);
}
catch { }
}
}
offset += 50;
}
}
}
}
// sort the tracks by playback count
var sortedTracks = unsortedTracks.OrderByDescending(t => t.Views);
foreach (TrackData t in sortedTracks)
tracks.Add(t);
}
catch (Exception e)
{
U.L(LogLevel.Warning, "soundcloud", "Could not fetch explore feed: " + e.Message);
VerifyConnectivity();
}
// run old code as backup
if (tracks.Count == 0)
{
string url = CreateURL("tracks", new string[] { "order=hotness", "limit=50" });
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
tracks = ParseTracks(JArray.Parse(reader.ReadToEnd()));
}
}
}
failedRequests = 0;
}
catch (Exception e)
{
U.L(LogLevel.Warning, "SOUNDCLOUD", "Could not retrieve top tracks: " + e.Message);
failedRequests++;
if (failedRequests < 3)
tracks = TopFeed();
else
VerifyConnectivity();
//.........这里部分代码省略.........