How to Access and Insert into the First Element of a List <> in WPF C# ?

MERUN KUMAR MAITY 531 Reputation points
2024-03-10T09:26:44.1033333+00:00

I have a List <> which I populate by showing available audio devices. The Audio Device List<> which is created by manipulating ancient Win32 APIs. My Code is working fine, currently there no issue present on it. But I have some requirement, regarding the displaying of the order of those audio devices.

I want a specific device at very First position and want another one at very Last position. The Code to show the device at very Last position is working very much efficiently but unfortunately the code to show the Device at First position is not working or you can say that I still can't figure it out.

Another off topic thing is, The very first and the very Last items on that List are pseudo items which I made through existing List items by tweaking their Win32 Device code.

My List is looking like this - _audioDevices = new List<AudioDevice>();

The Code to show the device at very Last position is -

_audioDevices.Insert(_audioDevices.Count - 0, new AudioDevice() { Name = "Selected application", Direction = "Recording", DeviceId = "Idlast", Default = false });

Now, comes into the Error part where I try to show the Device at very First position -

_audioDevices.Insert(_audioDevices.Count , new AudioDevice() { Name = "System default", Direction = "Playback", DeviceId = sIdDefaultRender, Default = true });

unfortunately the code to show the Device at First position is not working.

One important requirement is, The Device should be display always on top and it does not matter if there any item changes happen (Any items Added or Removed on the List) or not.

If you carefully see my code then you definitely look the code _audioDevices.Count - 0,

This is where we should manipulate to present our very first item always at top position.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,694 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,484 questions
{count} votes

Accepted answer
  1. gekka 7,741 Reputation points MVP
    2024-03-10T11:57:58.85+00:00

    To insert at the first of the list, let's set 0 to first parameter of Insert method.

    _audioDevices.Insert(0, new AudioDevice() { Name = "System default", Direction = "Playback", DeviceId = sIdDefaultRender, Default = true });
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful