Reputation: 130
Suppose I have simple "leg" Class defined by two points (actually PointIDs):
public class Leg
{
public int p1Id;
public int p2Id;
}
List of Legs are "interconnected", on the way that pt2 of one leg is same as pt1 of another leg (except first and last one). Let's initialize simple list:
var legs = new List<Leg>();
var l1 = new Leg { p1Id = 1, p2Id = 2 };
var l2 = new Leg { p1Id = 4, p2Id = 5 };
var l3 = new Leg { p1Id = 2, p2Id = 3 };
var l4 = new Leg { p1Id = 5, p2Id = 6 };
var l5 = new Leg { p1Id = 3, p2Id = 4 };
legs.Add(l1);
legs.Add(l2);
legs.Add(l3);
legs.Add(l4);
legs.Add(l5);
Fact is that this list of legs is not sorted, and of course IDs are not consecutive, like it is the case in this example.
Question is how to create function which will return list of consecutive points, between two given points, so:
var myLegs = FindMyLegs(legs, 5, 2);
.. should return following list : 5, 4, 3, 2
I guess it might be done by LINQ and inner join list of legs twice (legs1.pt2Id == legs2.pt1Id), but I am really not experienced in LINQ, and I can not find right way.
Basically I'll need some function:
List<int> FindMyLegs(List<Leg> allLegs, int startPt, int endPt) { ??? }
Upvotes: 0
Views: 118
Reputation: 10140
Hope it could help you:
public static List<int> FindMyLegs(List<Leg> allLegs, int startPt, int endPt)
{
var result = new List<int>();
var pre_result = allLegs.Where(l => (l.p1Id >= startPt && l.p2Id <= endPt) || (l.p2Id <= startPt && l.p1Id >= endPt));
foreach (var leg in pre_result)
{
result.Add(leg.p1Id);
result.Add(leg.p2Id);
}
result = (startPt > endPt ? result.OrderBy(t => t) : result.OrderByDescending(t => t)).Distinct().ToList();
return result;
}
static void Main()
{
var legs = new List<Leg>();
var l1 = new Leg { p1Id = 1, p2Id = 2 };
var l2 = new Leg { p1Id = 4, p2Id = 5 };
var l3 = new Leg { p1Id = 2, p2Id = 3 };
var l4 = new Leg { p1Id = 5, p2Id = 6 };
var l5 = new Leg { p1Id = 3, p2Id = 4 };
legs.Add(l1);
legs.Add(l2);
legs.Add(l3);
legs.Add(l4);
legs.Add(l5);
var myLegs = FindMyLegs(legs, 2, 5);
foreach (var leg in myLegs)
{
Console.WriteLine(leg);
}
}
Result:
var myLegs = FindMyLegs(legs, 2, 5);
5 4 3 2
var myLegs = FindMyLegs(legs, 4, 1);
1 2 3 4
Upvotes: 1
Reputation: 73472
I hope this is what you need
private List<int> FindMyLegs(List<Leg> allLegs, int startPt, int endPt)
{
return allLegs.Where(l => l.p1Id <= startPt && l.p1Id >=endPt).Select(l => l.p1Id).OrderByDescending(x => x).ToList();
}
Upvotes: 1
Reputation: 310947
If I understand your problem correctly, then I don't think that Linq will be the whole solution here. I think you'll need to build up a data structure that's suited to this kind of problem, and then choose appropriate algorithms to find your paths.
Take a look at Dijkstra's algorithm as a starting point.
Upvotes: 2