简体   繁体   中英

Using LINQ in cross-join query of a datatable in C#

I have an issue with using LINQ for cross-join query of a dataTable.

DataTable dt_edges = new DataTable();
dt_edges.Columns.Add("EdgeID", typeof(string));
dt_edges.Columns.Add("TriangleID", typeof(string));
dt_edges.Columns.Add("StartPointID", typeof(string));
dt_edges.Columns.Add("EndPointID", typeof(string));
dt_edges.Columns.Add("StartVerticeX", typeof(double));
dt_edges.Columns.Add("StartVerticeY", typeof(double));
dt_edges.Columns.Add("StartVerticeZ", typeof(double));
dt_edges.Columns.Add("EndVerticeX", typeof(double));
dt_edges.Columns.Add("EndVerticeY", typeof(double));
dt_edges.Columns.Add("EndVerticeZ", typeof(double));


var q = from a in dt_edges.AsEnumerable()
from b in dt_edges.AsEnumerable()

where (
a["StartVerticeX"].ToString() == b["StartVerticeX"].ToString()
&& a["StartVerticeY"].ToString() == b["StartVerticeY"].ToString()
&& a["EndVerticeX"].ToString() == b["EndVerticeX"].ToString()
&& a["EndVerticeY"].ToString() == b["EndVerticeY"].ToString()
)

select new { 
edgeID = a["EdgeID"],
aSVX = a["StartVerticeX"], 
aSVY = a["StartVerticeY"],
bSVZ = b["StartVerticeX"], 
bSVY = b["StartVerticeY"]
};

foreach (var item in q)
{
textBox2.Text += item.edgeID.ToString() + ": " + item.aSVX.ToString() + " " + item.aSVY.ToString() + ", " + item.bSVZ.ToString() + " " + item.bSVY.ToString() + "\n";
}

When I run the code, I have only 5 records in the dataTable, but the results of the count of the q is 225! When I check the results there are multiple repeats of the joined records and it seems that the filter does not really work properly.

What I'd like to do is to filter only those that have the StartX and StartY as well as EndX and EndY of the same in the dataTable. However, I haven't been able to resolve the issue.

Looking forward to your help. Cheers.

Rows with data in common? => group by !

var q = from a in dt_edges.AsEnumerable()
group a by new { sx = a["StartVerticeX"], 
                 sy = a["StartVerticeY"],
                 ex = a["EndVerticeX"],
                 ey = a["EndVerticeY"] } into g
where g.Count() > 1
from row in g select row;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM