简体   繁体   中英

Linq merging results

I'm working with a list within a list. This is how I'm currently searching:

var tags = from fd in BigList
           from tag in fd.Tags
           where tag.Id == selectedTag.Id ||
                 tag.Id == ID.TIMESTAMP
           select new { fd.Name, tag.Id, tag.Value };

I then iterate over the result-set and remembering when Timestamp pops up for the next entry, needless to say this is sloppy and I'm positive there's a better way using Linq, I just can't seem to find the syntax.

Here's some sample output ( Id indicates what type of data is stored inside eg a timestamp):

Name | Id | Value
-----|----|----------
0000 | 1  | <timestamp>
0000 | 2  | 1.2
...
9999 | 1  | <timestamp>
9999 | 2  | 6.3

I need all instances where Id = selectedTag.Id . I just want 1 list with Name , Id , Value and Timestamp , but the problem is my above attempt returns 2 entries for every item (1 for timestamp and 1 for the value). Is there a way to do this using Linq? Preferably using query syntax! :)

Here's a way to do it as a single query:

var tags = from fd in BigList
           from tag in fd.Tags
           where tag.Id == selectedTag.Id
           from tag2 in fd.Tags
           where tag.Id == ID.TIMESTAMP
           select new { fd.Name, id = tag.Value, timestamp = tag2.Value };

Here's a way to do it by joining two queries:

var tags = from fd in BigList
           from tag in fd.Tags
           where tag.Id == selectedTag.Id
           select new { fd.Name, id = tag.Value };
var tag2 = from fd in BigList
           from tag2 in fd.Tags
           where tag.Id == ID.TIMESTAMP
           select new { fd.Name, timestamp = tag2.Value };
var data = from id in tags
           join ts in tag2 on id.Name equals ts.Name
           select new { id.Name, id.id, ts.timestamp };

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