返回重复的方法。

时间:2015-07-07 17:20:12

标签: c# linq

我有这个方法返回策略并且它成功返回,除了它还返回重复项。

public void GetAllEligibleUnredeemedPoliciesForEachActiveAgentCodeForTheAgent()
    {
        AgentPoliciesForEachAgentCode = new List<DtoApp2LeadPolicy>();
        foreach (var agentCode in AllOfTheAgentCodesForTheAgent)
        {
            if (AgentPolicies != null) AgentPolicies.ToList().Clear();
            SetTheAgentCode(agentCode);
            SetAgentPolicyNumbersByAgentCode();
            SetAllPolicyNumbersByAgentsEligiblePolicies();
            SetAgentPoliciesFromAtlamServices();
            if(AgentPolicies != null) AgentPoliciesForEachAgentCode.AddRange(AgentPolicies);
        }
    }

所以我想添加

List<long> unique = longs.Distinct().ToList()  

我的问题是A)这是消除重复的正确方法吗? B)我的方法应该在何处以及如何插入?

我还尝试过这个,它说它包含一个无效的参数。

  public void GetAllEligibleUnredeemedPoliciesForEachActiveAgentCodeForTheAgent()
    {
        var AgentPoliciesForEachAgentCode = new List<DtoApp2LeadPolicy>();
        foreach (var agentCode in AllOfTheAgentCodesForTheAgent)
        {
            if (AgentPolicies != null) AgentPolicies.ToList().Clear();
            SetTheAgentCode(agentCode);
            SetAgentPolicyNumbersByAgentCode();
            SetAllPolicyNumbersByAgentsEligiblePolicies();
            SetAgentPoliciesFromAtlamServices();
            if(AgentPolicies != null && !AgentPoliciesForEachAgentCode.Contains(AgentPolicies))
            {
                AgentPoliciesForEachAgentCode.AddRange(AgentPolicies);
            }

        }
    }

2 个答案:

答案 0 :(得分:2)

  public void GetAllEligibleUnredeemedPoliciesForEachActiveAgentCodeForTheAgent()
    {
        var AgentPoliciesForEachAgentCode = new List<DtoApp2LeadPolicy>();
        foreach (var agentCode in AllOfTheAgentCodesForTheAgent.Distinct())
        {
            if (AgentPolicies != null) AgentPolicies.Clear();
            SetTheAgentCode(agentCode);
            SetAgentPolicyNumbersByAgentCode();
            SetAllPolicyNumbersByAgentsEligiblePolicies();
            SetAgentPoliciesFromAtlamServices();
            if (AgentPolicies != null )
            {
                AgentPoliciesForEachAgentCode.AddRange(AgentPolicies);
            }

        }
    }

因此,您只能通过唯一(不同)代理程序代码进行循环,并且不会将重复项添加到AgentPoliciesForEachAgentCode列表中。请尝试并让我知道

答案 1 :(得分:1)

您有重复项,因为您实际上从未清除AgentPoliciesToList()创建列表的新实例,然后清除那个实例,并丢失对它的引用,因为你没有将它缓存在变量中。

只需删除ToList(),您应该是金色的。

if (AgentPolicies != null) AgentPolicies.Clear();

或者你可以这样做:

if (AgentPolicies != null) AgentPolicies = new List<AgentPolicy>();