Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining Dictionary key that matches class List's list item into a new list - C#

So I have a Dictionarywith string values as Keys. And I have a class List:

listCoord = new List<Coord>();

whose class Coord looks like:

class Coord
{
    public string Segment { get; set; }
    public double startX { get; set; }
    public double startY { get; set; }
    public double endX { get; set; }
    public double endY { get; set; }
}

And it has around 12000 string Segment 's. My Dictionary's Keys are among the some of those segments. Now I need to join the segments that are in my Dictionary with those coordinate values that are in the List.

At first I went with the approach to use foreach and go trough each dictionary key to compare it with the list segments to find the matches. Then I've learned that LINQ can use SQL's inner joints to do the same thing.

Questions:

  1. What is the best way to find the matches between Dictionary Keys and certain list item?
  2. Once I do, how do I put it all into another List that contains the matching segment and its corresponding startX, startY, endX, endY values as list items.?

I apologize in advance if such question has already been asked and answered; personally couldn't find it.

like image 431
Romy Avatar asked Dec 24 '22 05:12

Romy


1 Answers

This is the way to join List & Dictionary (you will get only matching Coords)

 List<CoordNew> newlist = listCoord .Join(strDictionary, 
                                 a => a.Segment, //From listCoord
                                 b => b.Key, //From strDictionary
                                 (a, b) => new CoordNew() { 
                                      Segment_dictionaryValue = b.Value
                                      //Other values from list or dictionary
                                 }).ToList();

If you need CoordNew as

class CoordNew
{
    public string Segment { get; set; }
    public string Segment_dictionaryValue { get; set; }
    public double startX { get; set; }
    public double startY { get; set; }
    public double endX { get; set; }
    public double endY { get; set; }
}
like image 165
Lali Avatar answered Feb 01 '23 22:02

Lali