locked
How can we get the first item of the folowing SortedList RRS feed

  • Question

  • I would  like to get the first item in a Dictionary that uses a class.

    How can I do this if indexof is not available? I get error with the following code:

    SortedList<double,CarsRow> kvp = new SortedList<double,CarsRow>();
    
    foreach (KeyValuePair<double,CarsRow> item in keyArray.Value)
    {
    if (keyArray.Value[0].Equals(item)) // key not found in dictionary
    {
       //trying to get the first item from list only...
      // indexof doesn't work.
      //do something...
    }
    }
    
    
    private class CarsRow
    {
    public int SmallCars;
    public int BigCars;
    
    public CarsRow(int mySmallCars, int myBigCars)
    {
    SmallCars = mySmallCars;
    BigCars = myBigCars;
    }
    }
    
    
    
    



    • Edited by r3nv Tuesday, July 7, 2020 3:02 AM
    Monday, July 6, 2020 11:29 PM

All replies

  • Hi r3nv,

    Thank you for posting here.

    Please refer to the following code to get data from Dictionary.

                Dictionary<double, CarsRow> kvp = new Dictionary<double, CarsRow>();
                kvp.Add(1, new CarsRow(100, 101));
                kvp.Add(2, new CarsRow(100, 101));
                kvp.Add(3, new CarsRow(100, 101));
                kvp.Add(4, new CarsRow(100, 101));
    
                CarsRow re = kvp[1]; // get value by key.
                KeyValuePair<double,CarsRow> re1 = kvp.ElementAt(0);// get kvp by index.
    
                Console.WriteLine(re.SmallCars + " " + re.BigCars);
                Console.WriteLine(re1.Value.SmallCars + " " + re1.Value.BigCars);

    I wrote two ways to do it, the first one is to get the value according to the key, the second is to obtain a KeyValuePair<K,V> according to the index.

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, July 7, 2020 2:08 AM
  • Thanks I'll try tomorrow and let you know.
    Tuesday, July 7, 2020 2:39 AM
  • I apologize.  I'm using a SortedList not a dictionary.  Those conversions don't work.

    Tuesday, July 7, 2020 3:02 AM
  • If you wanted to find by key or first value

    public class CarsRow : IEquatable<CarsRow>
    {
        public int SmallCars { get; set; }
        public int BigCars { get; set; }
    
        public bool Equals(CarsRow other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return SmallCars == other.SmallCars && BigCars == other.BigCars;
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((CarsRow) obj);
        }
    
        public override int GetHashCode()
        {
            unchecked
            {
                return (SmallCars * 397) ^ BigCars;
            }
        }
    }

    Test it

    var kvp = new Dictionary<double, CarsRow>()
    {
        {100, new CarsRow() {SmallCars = 1, BigCars = 2}},
        {101, new CarsRow() {SmallCars = 3, BigCars = 12}},
        {102, new CarsRow() {SmallCars = 8, BigCars = 44}}
    };
    
    var testCar = new CarsRow() { SmallCars = 1, BigCars = 2};
    
    if (kvp.ContainsValue(testCar)) 
    {
        var foundBykey = kvp
            .FirstOrDefault(carRow => carRow.Value.Equals(testCar));
        MessageBox.Show("Found by value good to go");
    }
    
    if (kvp.ContainsKey(102))
    {
        var foundByKey = kvp[102];
        MessageBox.Show("Found by key");
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Tuesday, July 7, 2020 3:19 AM
  • Use LINQ's FirstOrDefault.

    var kvp = new SortedList<double, CarsRow>() {
        { 1, new CarsRow(1, 2) },
        { 2, new CarsRow(3, 4) },
        { 3, new CarsRow(5, 6) },
    };
    
    var item = new CarsRow(3, 4);
    
    var car = kvp.FirstOrDefault(k => k.Value?.Equals(item) ?? false);            

    Of course `Equals` does equality comparison which doesn't work on reference types. Option 1 is to implement `IEqualityComparer` as Karen demoed. Option 2 is to do it inline if you only need it here.

    var car = kvp.FirstOrDefault(k => k.Value != null && k.Value.SmallCars == item.SmallCars && k.Value.BigCars == item.BigCars);            

    Or better yet a helper method.

    var car = kvp.FirstOrDefault(k => CarsAreEqual(k.Value, item));            
    
    //Local function
    bool CarsAreEqual ( CarsRow left, CarsRow right )
    {
        if (left == null) 
            return right != null;
        else if (right == null)
            return false;
    
        if (left == right) 
            return true;
    
        return left.SmallCars == right.SmallCars && left.BigCars == right.BigCars;
    }


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Naomi N Tuesday, July 7, 2020 1:46 PM
    Tuesday, July 7, 2020 1:32 PM
  • Hi,

    Has your issue been resolved?

    If so, please click on the "Mark as answer" option of the reply that solved your question, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 13, 2020 9:52 AM
  • Hi

                var kvp = new SortedList<double, CarsRow>() {
                    { 1, new CarsRow(1, 2) },
                    { 2, new CarsRow(3, 4) },
                    { 3, new CarsRow(5, 6) },
                };
                var item = new CarsRow(4, 4);
    
                var carisavailable = kvp.Where(k => k.Value.BigCars == item.BigCars).Count() > 0 ? true: false;
                Console.ReadLine();

    Thanks and regards

    Saturday, July 18, 2020 10:52 AM