gpt4 book ai didi

c# - Linq自连接查询

转载 作者:行者123 更新时间:2023-11-30 15:06:34 24 4
gpt4 key购买 nike

我需要一些有关 Linq 自连接的帮助。

我有以下类(class):

public class Owner
{
public string OwnerId {get;set;}
public string Name {get;set;}
public string Area {get;set;}
public string City {get;set;}
public string Sex {get;set;}
public List<Dog> dog {get;set;}
}

还有 table ....

ID OwnerId OwnerName TypeId TypeName   TypeValue        TypeCodeId
1 1 John 1 Area United States 440
2 1 John 2 City Los-Angeles 221
3 1 John 3 Sex Female 122
4 2 Mary 1 Area Mexico 321
4 2 Mary 2 City Cancun 345
............................................................

我需要尽可能快地将表 1 的结果解析为所有者列表。注意:类型可以为空,但我仍然需要显示该所有者(因此,我认为左连接应该有效)。

这是我的工作。 (owners 是一个包含 table1 结果的 webservice 类)

public IEnumerable<Owner> GetOwners() { 
return (from owner in owners
join area in owners into owner_area
from oa in owner_area.DefaultIfEmpty()
join City in owners into owner_city
from oc in owner_city.DefaultIfEmpty()
join sex in owners into owner_sex
from os in owner_sex.DefaultIfEmpty()
where oa.TypeId == 1 && oc.TypeId ==2 && os.TypeId ==3
select new Owner() {OwnerId = owner.OwnerId,
Name = owner.Name,
Area = oa.TypeValue,
City = oc.TypeValue,
Sex = os.TypeValue}).Distinct();
}

这个查询有几个问题:

  1. 它返回多个结果,但 distinct 没有按预期工作
  2. 我试过使用 GroupBy,但它说不能将 Owner 隐式转换为 IEnumerable <int, Owner>
  3. super 慢

如何通过自连接获得不同的记录并提高性能?谢谢

更新:谢谢你们的回答,现在正在测试,但我发现我忘了再提供一件事。我在表格布局中添加了一个名为 TypeCodeId 的新列(见上文)用户可以根据他们的选择过滤值。所以,我有 Area、City 和 Sex 的 TypeCodeId + TypeValue 字典。所有这些参数都是可选的(如果用户没有选择任何参数,我只向他们显示所有记录。

因此,假设用户选择了过滤器 Area: Unites States和过滤器 City: Los Angeles

我的查询看起来像这样:

Select Projects where Area equals United States(440) and City equals Los Angeles(221)

如果只选择了 Area:Mexico,那么我的查询将是这样的:

Select Projects where Area equals Mexico(321)

我不确定如何使用您在示例中提供的内容来执行可选的 where 子句。

最佳答案

由于表未规范化,我们需要从对象/表中获取不同的用户。这可以通过以下方式实现:

owners.Select(o => new { o.OwnerId, o.OwnerName }).Distinct()

然后我们需要用两个匹配值连接“类型”,一个用于 ownerId,另一个用于特定类型。

var ownerQuery =
from o in owners.Select(o => new { o.OwnerId, o.OwnerName }).Distinct()

join area in owners on new { o.OwnerId, TypeId = 1 } equals new { area.OwnerId, area.TypeId } into areas
from area in areas.DefaultIfEmpty()

join city in owners on new { o.OwnerId, TypeId = 2 } equals new { city.OwnerId, city.TypeId } into cities
from city in cities.DefaultIfEmpty()

join sex in owners on new { o.OwnerId, TypeId = 3 } equals new { sex.OwnerId, sex.TypeId } into sexes
from sex in sexes.DefaultIfEmpty()

select new
{
owner = o,
Area = (area != null) ? area.TypeValue : null,
City = (city != null) ? city.TypeValue : null,
Sex = (sex != null) ? sex.TypeValue : null,
};

您可能需要更改上面示例中的投影。

关于c# - Linq自连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com