我编辑我的帖子,因为假设3方法从数据库表中返回行 表是:docTags,标签和docs docTags是中间表 一个文档(文档)可以有许多标记,一个标记可以属于许多文档 我怎么得到:TagKey =“123”其中docTags.Add(新配置(1,1)); 课程 {
static void Main(string[] args)
{
}
}
public class Configuration
{
public int DocID { get; set; }
public int TagID { get; set; }
public string Name { get; set; }
public string DocKey { get; set; }
public string TagKey { get; set; }
public Configuration(int _docId,string _name, string _docKey)
{
DocID = _docId;
Name = _name;
DocKey = _docKey;
}
public Configuration(int _tagId,string name, string _dockey,string _tagKey)
{
TagID = _tagId;
Name = name;
TagKey = _tagKey;
}
public Configuration(int _tagId, int _docId)
{
TagID = _tagId;
DocID = _docId;
}
public static List<Configuration> getDocType()
{
List<Configuration> docs = new List<Configuration>();
docs.Add(new Configuration(1,"contract", "xxx"));
docs.Add(new Configuration(2,"Action", "yyy"));
return docs;
}
public static List<Configuration> getTagName()
{
List<Configuration> tags = new List<Configuration>();
tags.Add(new Configuration( 1,"contractid", "123"));
tags.Add(new Configuration(2,"SuperDuper", "332123"));
tags.Add(new Configuration(22, "rama", "yyy"));
tags.Add(new Configuration(32, "aktiv", "123456"));
tags.Add(new Configuration(42, "data ","xx764fhx"));
return tags;
}
public static List<Configuration> getDocTags()
{
List<Configuration> docTags = new List<Configuration>();
docTags.Add(new Configuration(1, 2));
docTags.Add(new Configuration(1, 1));
docTags.Add(new Configuration(1, 22));
docTags.Add(new Configuration(2, 2));
docTags.Add(new Configuration(2, 32));
return docTags;
}
}
}
答案 0 :(得分:5)
您需要Join
:
var commonUsers = (from t in tags
join d in docs on t.DocKey equals d.DocKey
select t)
.Distinct(); // to remove duplicates
或另一种方式
var commonUsers = tags.Where(t => docs.Any(d => d.DocKey == t.DocKey));
第二种方法较短,但第一种方法可能表现更好。
答案 1 :(得分:1)
var newList = docs.Intersect(tags);
您可能需要覆盖Equals运算符才能生效。
答案 2 :(得分:1)
以下是使用Intersect执行此操作而不重载Equals方法的方法。您需要创建一个新类作为IEqualityComparer
class ConfigurationComparer : IEqualityComparer<Configuration>
{
//You can change which string comparer fits your needs best.
private readonly StringComparer comparer = StringComparer.CurrentCulture;
public bool Equals(Configuration x, Configuration y)
{
return comparer.Equals(x.DocKey,y.DocKey);
}
public int GetHashCode(Configuration obj)
{
return comparer.GetHashCode(obj.DocKey);
}
}
然后你只需做
var newList = tags.Intersect(docs, new ConfigurationComparer());
答案 3 :(得分:0)
您可以使用Contains
方法并将其应用于具有lambda表达式的过滤器,以使用一个或多个条件从另一个列表中提取项目,以获取样本:
var result = needThis.Where(x => needThis2.Contains(x)).ToList();
或者使用扩展方法Intersect
作为示例:
var result = needThis.Intersect(needThis2);