我想将以下for循环代码转换为LINQ以提高可读性。 for循环工作正常。然而,LINQ给了我错误,任何人都可以指出我错误的地方吗?
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);
}
我的错误LINQ就像:
var edges = dataset.Select(e => new GraphEdge
{
Source = e.SourceMachine.Trim(),
Target = e.TargetMachine.Trim(),
Weight = e.Connection
}).ToList();
仅供参考:
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; }
}
更新GraphEdge类
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; }
}
答案 0 :(得分:1)
虽然在这里使用linq似乎并不合适,但如果你想要,你仍然可以尝试:
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();
希望它有所帮助。
答案 1 :(得分:0)
你在做的不是Linq。你正在一个类中初始化变量试试这样的事情。
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; }
}
}
}
答案 2 :(得分:0)
GraphEdge没有默认构造函数(没有参数的构造函数)。我怀疑这样做会很好:
var edges = dataset.Select(e => new GraphEdge(
e.SourceMachine.Trim(),
e.TargetMachine.Trim(),
e.Connection)).ToList();