Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of related objects whose type is in array of types

Tags:

c#

linq

I have a function that (via ajax) I pass a Guid and a comma delimited string of the types of objects I would like to return . I'm having trouble building a link statement that only returns the desired types. I'm struggling with how to build the query to check if string[] relatedTypes matches rw.GetType().Name. Or perhaps there's a better way.

Here's the Model...

public abstract class WebObject : IValidatableObject
{
    public WebObject()
    {
        this.Id = Guid.NewGuid();
        RelatedTags = new List<Tag>();
        RelatedWebObjects = new List<WebObject>();
    }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid Id { get; set; }
    public virtual ICollection<WebObject> RelatedWebObjects { get; set; }
    public IList<Guid> RelatedWebObjectIds { get; set; }
}

And here's my function

public JsonResult GetRelatedWebObjectsByWebObject(Guid id, string relatedWebObjectTypes)
{
    JsonResult result = new JsonResult();
    Guid webSiteId = db.WebObjects.Find(id).WebSiteId;
    string[] relatedTypes = relatedWebObjectTypes.Split(',');
    var resultData = (from w in db.WebObjects
                      where w.Id == id
                      from rw in w.RelatedWebObjects
                      where rw.GetType().Name.Contains(relatedTypes)
                      select rw.Id).ToList();

    result.Data = resultData;
    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    return result;
}
like image 597
bflemi3 Avatar asked Dec 01 '25 21:12

bflemi3


1 Answers

Are you looking for something like:

var relatedTypes = new HashSet<string>(relatedWebObjectTypes);
var resultData = (from w in db.WebObjects
                  where w.Id == id
                    &&  relatedTypes.SetEquals
                          (w.RelatedWebObjects.Select(rwo => rwo.GetType().Name))

                  select w.RelatedWebObjectIds).ToList();

Although I would say that it isn't good practice to use a collection of simple type names in this manner. Are you sure you couldn't use a Type[] or similar here?

like image 169
Ani Avatar answered Dec 03 '25 11:12

Ani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!