Programmerzzz
Programmerzzz

Reputation: 1287

Remove First & Last Items from a List of string

Have a Dictionary <string,string> as follows.

var d = new Dictionary<string, string>
            {
                { "d.b.f", "x1" },
                { "d.z.x.f", "x2" },
                { "d.y.f.x.f", "x3" }
            };

Want to construct a new Dictionary with first (d) & last (f) excluded from each key in dictionary. So result looks

var res = new Dictionary<string, string>
            {
                { "b", "x1" },
                { "z.x", "x2" },
                { "y.f.x", "x3" }
            };

I tried as follows.

var abc = d.Select(x => Helper(x));

        private static KeyValuePair<string,string> Helper(KeyValuePair<string,string> x)
        {
            var array =  x.Key.Split('.').ToList();
            return new KeyValuePair<string, string>(string.Join(".", array.Where(z => array.IndexOf(z) != 0 && array.IndexOf(z) != array.Count - 1)), x.Value);
        }

now abc has my required result. Is there an efficient way to do the same thing?

Upvotes: 0

Views: 69

Answers (1)

Ibrennan208
Ibrennan208

Reputation: 1402

If you know that you will always have d. in front, and .f on the end, you could simply do a substring of your key.

        private static KeyValuePair<string, string> Helper(KeyValuePair<string, string> x)
        {
            // starting index of 2, to skip "d.", and length of the key minus "d." and ".f"
            var substring = x.Key.Substring(2, x.Key.Length - 4);
            return new KeyValuePair<string, string>(substring, x.Value);
        }

Alternatively, if you will actually have more characters in front and behind (instead of just d. and .f), you could calculate the index of the first . and last . and then create a substring from that:

        private static KeyValuePair<string, string> Helper(KeyValuePair<string, string> x)
        {
            // d.b.f
            var startIndex = x.Key.IndexOf('.') + 1; // 2
            var endIndex = x.Key.LastIndexOf('.'); // 3
            var length = endIndex - startIndex; // 1
            var substring = x.Key.Substring(startIndex, length); // b
            return new KeyValuePair<string, string>(substring, x.Value);
        }

Upvotes: 1

Related Questions