Reputation: 692
I want to convert the following for-loop code into LINQ to improve readability. The for loop works fine. However, LINQ gave me errors and can anyone point me out where I made mistake?
for (int i = 1; i <= dataset.Count(); i++)
{
string source = dataset.First(e => e.ID == i).SourceMachine.Trim();
string target = dataset.First(e => e.ID == i).TargetMachine.Trim();
int count = dataset.First(e => e.ID == i).Connection;
GraphEdge edge = new GraphEdge(source, target, count);
edgeList.Add(edge);
}
MY wrong LINQ is like:
var edges = dataset.Select(e => new GraphEdge
{
Source = e.SourceMachine.Trim(),
Target = e.TargetMachine.Trim(),
Weight = e.Connection
}).ToList();
FYI:
IQueryable<SeedTest> dataset = builder.GetAllSeedTest();
public partial class SeedTest
{
public string SourceMachine { get; set; }
public string TargetMachine { get; set; }
public int Connection { get; set; }
public int ID { get; set; }
}
Update GraphEdge class
public class GraphEdge : IEdge<string>
{
public GraphEdge(string s, string t, int w)
{
Source = s;
Target = t;
Weight = w;
}
public string Source { get; set; }
public string Target { get; set; }
public int Weight { get; set; }
}
Upvotes: 1
Views: 44
Reputation: 12768
GraphEdge doesn't have a default constructor (one with no parameters). I suspect this would work just fine:
var edges = dataset.Select(e => new GraphEdge(
e.SourceMachine.Trim(),
e.TargetMachine.Trim(),
e.Connection)).ToList();
Upvotes: 0
Reputation: 561
Although it does not seem advantageous to use linq here but still if you want you can try:
var edges = dataset.Select(t =>
{
var obj = dataset.First(m => dataset.IndexOf(t).Equals(t.ID));
return new GraphEdge(obj.SourceMachine.Trim(), obj.TargetMachine.Trim(), obj.Connection);
}).ToArray();
Hope it helps.
Upvotes: 1
Reputation: 34419
What you are doing is not Linq. You are intializing variable in a class Try something like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
GraphEdge graphEdge = new GraphEdge();
var edges = graphEdge.dataset.Select(e => new GraphEdge()
{
Source = e.SourceMachine.Trim(),
Target = e.TargetMachine.Trim(),
Weight = e.Connection
}).ToList();
}
}
public class GraphEdge
{
public string Source { get; set; }
public string Target { get; set; }
public int Weight { get; set; }
public IQueryable<SeedTest> dataset = builder.GetAllSeedTest();
public GraphEdge()
{
}
public GraphEdge(string s, string t, int w)
{
Source = s;
Target = t;
Weight = w;
}
public partial class SeedTest
{
public string SourceMachine { get; set; }
public string TargetMachine { get; set; }
public int Connection { get; set; }
public int ID { get; set; }
}
}
}
Upvotes: 0