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

MERUN KUMAR MAITY 636 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.

Developer technologies Windows Presentation Foundation
Developer technologies C#
{count} votes

Accepted answer
  1. gekka 12,206 Reputation points MVP Volunteer Moderator
    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.